Module: RakeScript::FileSystem

Included in:
RakeMethods
Defined in:
lib/rake_script/file_system.rb

Instance Method Summary collapse

Instance Method Details

#append_file(filepath, string, verbose: false, before: nil, after: nil) ⇒ Object

Raises:

  • (ArgumentError)


57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/rake_script/file_system.rb', line 57

def append_file(filepath, string, verbose: false, before: nil, after: nil)
  raise ArgumentError, "can't use :before and :after in same time" if before && after

  after_index = nil
  if after || before
    content = File.read(filepath)
    after_index = content.index(after || before)
    return if after_index.nil?
  end
  after_index -= before.size if after_index && before

  File.open(filepath, 'a+') do |f|
    f.seek(after_index, IO::SEEK_SET) if after_index
    f.write(string)
  end
  puts("Append #{string.inspect} to #{filepath}") if verbose
end

#chdir(path) ⇒ Object



53
54
55
# File 'lib/rake_script/file_system.rb', line 53

def chdir(path)
  Dir.chdir(path) { yield }
end

#copy(from, to, options = {}) ⇒ Object



39
40
41
42
43
44
# File 'lib/rake_script/file_system.rb', line 39

def copy(from, to, options = {})
  # from = from.include?('*') ? Dir.glob(from) : [from]
  # from.each { |f| FileUtils.cp(f, to, options) }
  flags = posix_flags('-v': !!options[:verbose])
  cmd('cp', *flags, from, to)
end

#copy_r(from, to, options = {}) ⇒ Object



46
47
48
49
50
51
# File 'lib/rake_script/file_system.rb', line 46

def copy_r(from, to, options = {})
  # from = from.include?('*') ? Dir.glob(from) : [from]
  # from.each { |f| FileUtils.cp_r(f, to, options) }
  flags = posix_flags('-r', '-v': !!options[:verbose])
  cmd('cp', *flags, from, to)
end

#create_dir_p(*paths) ⇒ Object



32
33
34
35
36
37
# File 'lib/rake_script/file_system.rb', line 32

def create_dir_p(*paths)
  options = paths.last.is_a?(Hash) ? paths.pop : {}
  # FileUtils.mkdir_p(paths, options)
  flags = posix_flags('-p', '-v': !!options[:verbose])
  cmd('mkdir', *flags, *paths)
end

#folder_exist?(path) ⇒ TruClass, FalseClass

Check if folder exists.

Parameters:

  • path (String)

    folder path.

Returns:

  • (TruClass, FalseClass)

    boolean



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

def folder_exist?(path)
  File.directory?(path)
end

#posix_flags(*flags) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/rake_script/file_system.rb', line 12

def posix_flags(*flags)
  result = []
  flags.each do |flag|
    if flag.is_a?(Hash)
      result.concat(
          flag.reject { |_, v| !v }.map { |k, v| v.is_a?(TrueClass) ? k.to_s : "#{k}=#{v}" }
      )
    else
      result.push(flag.to_s)
    end
  end
  result
end

#remove_rf(*paths) ⇒ Object



26
27
28
29
30
# File 'lib/rake_script/file_system.rb', line 26

def remove_rf(*paths)
  options = paths.last.is_a?(Hash) ? paths.pop : {}
  flags = posix_flags('-rf', '-v': !!options[:verbose])
  cmd('rm', *flags, *paths)
end