Module: Sevgi::Function::File

Included in:
Sevgi::Function
Defined in:
lib/sevgi/function/file.rb

Instance Method Summary collapse

Instance Method Details

#changed?(file, content, &filter) ⇒ Boolean

Returns:

  • (Boolean)


9
10
11
12
13
14
15
16
# File 'lib/sevgi/function/file.rb', line 9

def changed?(file, content, &filter)
  return true unless ::File.exist?(file)

  old_content = ::File.read(file)
  old_content, content = [old_content, content].map(&filter) if filter

  Digest::SHA1.digest(old_content) != Digest::SHA1.digest(content)
end

#existing(file, extensions) ⇒ Object



18
19
20
21
22
23
24
# File 'lib/sevgi/function/file.rb', line 18

def existing(file, extensions)
  return file if ::File.exist?(file)
  return nil unless ::File.extname(file).empty?
  return nil if extensions.empty?

  extensions.map { |ext| "#{file}.#{ext}" }.detect { |file| ::File.exist?(file) }
end

#existing!(file, extensions) ⇒ Object



26
27
28
29
30
# File 'lib/sevgi/function/file.rb', line 26

def existing!(file, extensions)
  existing(file, extensions).tap do |found|
    raise ArgumentError, "No matching file(s) found: #{file}" unless found
  end
end

#existings(*files, extensions: []) ⇒ Object



32
33
34
35
36
# File 'lib/sevgi/function/file.rb', line 32

def existings(*files, extensions: [])
  {}.tap do |existings|
    files.compact.each { |file| existings[file] = existing(file, extensions) }
  end
end

#existings!Object

Raises:



38
39
40
41
42
43
44
45
# File 'lib/sevgi/function/file.rb', line 38

def existings!(...)
  existings = F.existings(...)
  missings = existings.select { |_, match| match.nil? }.keys

  raise ArgumentError, "No matching file(s) found: #{missings.join(", ")}" unless missings.empty?

  existings
end

#out(content, *paths, &filter) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/sevgi/function/file.rb', line 47

def out(content, *paths, &filter)
  if paths.empty?
    ::Kernel.puts(content)
  else
    file = ::File.expand_path(::File.join(*paths))
    output = "#{content.chomp}\n"

    return unless changed?(file, output, &filter)

    file.tap { ::File.write(file, output) }
  end
end

#qualify(file, default_extension) ⇒ Object



60
61
62
63
64
# File 'lib/sevgi/function/file.rb', line 60

def qualify(file, default_extension)
  return file unless ::File.extname(file).empty?

  "#{file}.#{default_extension}"
end

#subext(ext, *paths) ⇒ Object

Adapted from ActiveSupport



67
68
69
70
71
72
73
74
75
76
# File 'lib/sevgi/function/file.rb', line 67

def subext(ext, *paths)
  path = ::File.join(*paths)

  return path if %w[. ..].include?(path)
  return path unless ext

  ext = ".#{ext}" unless ext.empty? || ext.start_with?(".")

  Pathname.new(path).sub_ext(ext).to_s
end

#touch(*paths) ⇒ Object



78
79
80
81
82
83
# File 'lib/sevgi/function/file.rb', line 78

def touch(*paths)
  ::File.join(*paths).tap do |path|
    ::FileUtils.mkdir_p(::File.dirname(path))
    ::FileUtils.touch(path)
  end
end