Module: TTY::File

Defined in:
lib/tty/file.rb,
lib/tty/file/differ.rb,
lib/tty/file/version.rb,
lib/tty/file/create_file.rb,
lib/tty/file/digest_file.rb,
lib/tty/file/download_file.rb

Defined Under Namespace

Classes: CreateFile, Differ, DigestFile, DownloadFile

Constant Summary collapse

InvalidPathError =

Invalid path erorr

Class.new(ArgumentError)
U_R =

File permissions

0400
U_W =
0200
U_X =
0100
G_R =
0040
G_W =
0020
G_X =
0010
O_R =
0004
O_W =
0002
O_X =
0001
A_R =
0444
A_W =
0222
A_X =
0111
VERSION =
'0.7.0'
DownloadError =
Class.new(StandardError)

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.add_fileObject

Create new file if doesn’t exist

Examples:

create_file('doc/README.md', '# Title header')
create_file 'doc/README.md' do
  '# Title Header'
end

Parameters:

  • relative_path (String)
  • content (String|nil)

    the content to add to file

  • options (Hash)


209
210
211
212
213
# File 'lib/tty/file.rb', line 209

def create_file(relative_path, *args, **options, &block)
  content = block_given? ? block[] : args.join

  CreateFile.new(self, relative_path, content, options).call
end

.add_to_fileObject

Append to a file

Examples:

append_to_file('Gemfile', "gem 'tty'")
append_to_file('Gemfile') do
  "gem 'tty'"
end

Parameters:

  • relative_path (String)
  • content (Array[String])

    the content to append to file



480
481
482
483
484
485
# File 'lib/tty/file.rb', line 480

def append_to_file(relative_path, *args, **options, &block)
  log_status(:append, relative_path, options.fetch(:verbose, true),
                                     options.fetch(:color, :green))
  options.merge!(after: /\z/, verbose: false)
  inject_into_file(relative_path, *(args << options), &block)
end

.append_to_file(relative_path, *args, **options, &block) ⇒ Object

Append to a file

Examples:

append_to_file('Gemfile', "gem 'tty'")
append_to_file('Gemfile') do
  "gem 'tty'"
end

Parameters:

  • relative_path (String)
  • content (Array[String])

    the content to append to file



472
473
474
475
476
477
# File 'lib/tty/file.rb', line 472

def append_to_file(relative_path, *args, **options, &block)
  log_status(:append, relative_path, options.fetch(:verbose, true),
                                     options.fetch(:color, :green))
  options.merge!(after: /\z/, verbose: false)
  inject_into_file(relative_path, *(args << options), &block)
end

.binary?(relative_path) ⇒ Boolean

Check if file is binary

Examples:

binary?('Gemfile') # => false
binary?('image.jpg') # => true

Parameters:

  • relative_path (String)

    the path to file to check

Returns:

  • (Boolean)

    Returns ‘true` if the file is binary, `false` otherwise



53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/tty/file.rb', line 53

def binary?(relative_path)
  bytes = ::File.new(relative_path).size
  bytes = 2**12 if bytes > 2**12
  buffer = ::File.read(relative_path, bytes, 0) || ''
  buffer = buffer.force_encoding(Encoding.default_external)
  begin
    return buffer !~ /\A[\s[[:print:]]]*\z/m
  rescue ArgumentError => error
    return true if error.message =~ /invalid byte sequence/
    raise
  end
end

.checksum_file(source, *args, **options) ⇒ String

Create checksum for a file, io or string objects

Examples:

checksum_file('/path/to/file')
checksum_file('Some string content', 'md5')

Parameters:

  • source (File, IO, String)

    the source to generate checksum for

  • mode (String)
  • options (Hash[Symbol])

Options Hash (**options):

  • :noop (String)

    No operation

Returns:

  • (String)

    the generated hex value



86
87
88
89
90
# File 'lib/tty/file.rb', line 86

def checksum_file(source, *args, **options)
  mode     = args.size.zero? ? 'sha256' : args.pop
  digester = DigestFile.new(source, mode, options)
  digester.call unless options[:noop]
end

.chmod(relative_path, permissions, **options) ⇒ Object

Change file permissions

Examples:

chmod('Gemfile', 0755)
chmod('Gemilfe', TTY::File::U_R | TTY::File::U_W)
chmod('Gemfile', 'u+x,g+x')

Parameters:

  • relative_path (String)
  • permisssions (Integer, String)
  • options (Hash[Symbol])

Options Hash (**options):

  • :noop (Symbol)
  • :verbose (Symbol)
  • :force (Symbol)


112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
# File 'lib/tty/file.rb', line 112

def chmod(relative_path, permissions, **options)
  mode = ::File.lstat(relative_path).mode
  if permissions.to_s =~ /\d+/
    mode = permissions
  else
    permissions.scan(/[ugoa][+-=][rwx]+/) do |setting|
      who, action = setting[0], setting[1]
      setting[2..setting.size].each_byte do |perm|
        mask = const_get("#{who.upcase}_#{perm.chr.upcase}")
        (action == '+') ? mode |= mask : mode ^= mask
      end
    end
  end
  log_status(:chmod, relative_path, options.fetch(:verbose, true),
                                    options.fetch(:color, :green))
  ::FileUtils.chmod_R(mode, relative_path) unless options[:noop]
end

.copy_dirObject

Copy directory recursively from source to destination path

Any files names wrapped within % sign will be expanded by executing corresponding method and inserting its value. Assuming the following directory structure:

app/
  %name%.rb
  command.rb.erb
  README.md

Invoking:
  copy_directory("app", "new_app")
The following directory structure should be created where
name resolves to 'cli' value:

new_app/
  cli.rb
  command.rb
  README

Examples:

copy_directory("app", "new_app", recursive: false)
copy_directory("app", "new_app", exclude: /docs/)

Parameters:

  • options (Hash[Symbol])


325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
# File 'lib/tty/file.rb', line 325

def copy_directory(source_path, *args, **options, &block)
  check_path(source_path)
  source = escape_glob_path(source_path)
  dest_path = args.first || source
  opts = {recursive: true}.merge(options)
  pattern = opts[:recursive] ? ::File.join(source, '**') : source
  glob_pattern = ::File.join(pattern, '*')

  Dir.glob(glob_pattern, ::File::FNM_DOTMATCH).sort.each do |file_source|
    next if ::File.directory?(file_source)
    next if opts[:exclude] && file_source.match(opts[:exclude])

    dest = ::File.join(dest_path, file_source.gsub(source_path, '.'))
    file_dest = ::Pathname.new(dest).cleanpath.to_s

    copy_file(file_source, file_dest, **options, &block)
  end
end

.copy_directory(source_path, *args, **options, &block) ⇒ Object

Copy directory recursively from source to destination path

Any files names wrapped within % sign will be expanded by executing corresponding method and inserting its value. Assuming the following directory structure:

app/
  %name%.rb
  command.rb.erb
  README.md

Invoking:
  copy_directory("app", "new_app")
The following directory structure should be created where
name resolves to 'cli' value:

new_app/
  cli.rb
  command.rb
  README

Examples:

copy_directory("app", "new_app", recursive: false)
copy_directory("app", "new_app", exclude: /docs/)

Parameters:

  • options (Hash[Symbol])

Options Hash (**options):

  • :preserve (Symbol)

    If true, the owner, group, permissions and modified time are preserved on the copied file, defaults to false.

  • :recursive (Symbol)

    If false, copies only top level files, defaults to true.

  • :exclude (Symbol)

    A regex that specifies files to ignore when copying.



305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
# File 'lib/tty/file.rb', line 305

def copy_directory(source_path, *args, **options, &block)
  check_path(source_path)
  source = escape_glob_path(source_path)
  dest_path = args.first || source
  opts = {recursive: true}.merge(options)
  pattern = opts[:recursive] ? ::File.join(source, '**') : source
  glob_pattern = ::File.join(pattern, '*')

  Dir.glob(glob_pattern, ::File::FNM_DOTMATCH).sort.each do |file_source|
    next if ::File.directory?(file_source)
    next if opts[:exclude] && file_source.match(opts[:exclude])

    dest = ::File.join(dest_path, file_source.gsub(source_path, '.'))
    file_dest = ::Pathname.new(dest).cleanpath.to_s

    copy_file(file_source, file_dest, **options, &block)
  end
end

.copy_file(source_path, *args, **options, &block) ⇒ Object

Copy file from the relative source to the relative destination running it through ERB.

Examples:

copy_file 'templates/test.rb', 'app/test.rb'
vars = OpenStruct.new
vars[:name] = 'foo'
copy_file 'templates/%name%.rb', 'app/%name%.rb', context: vars

Parameters:

  • options (Hash)

Options Hash (**options):

  • :context (Symbol)

    the binding to use for the template

  • :preserve (Symbol)

    If true, the owner, group, permissions and modified time are preserved on the copied file, defaults to false.

  • :noop (Symbol)

    If true do not execute the action.

  • :verbose (Symbol)

    If true log the action status to stdout



235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
# File 'lib/tty/file.rb', line 235

def copy_file(source_path, *args, **options, &block)
  dest_path = (args.first || source_path).sub(/\.erb$/, '')

  ctx = if (vars = options[:context])
          vars.instance_eval('binding')
        else
          instance_eval('binding')
        end

  create_file(dest_path, options) do
    template = ERB.new(::File.binread(source_path), nil, "-", "@output_buffer")
    content = template.result(ctx)
    content = block[content] if block
    content
  end
  return unless options[:preserve]
  (source_path, dest_path, options)
end

.copy_metadata(src_path, dest_path, **options) ⇒ Object

Copy file metadata

Parameters:

  • src_path (String)

    the source file path

  • dest_path (String)

    the destination file path



263
264
265
266
267
# File 'lib/tty/file.rb', line 263

def (src_path, dest_path, **options)
  stats = ::File.lstat(src_path)
  ::File.utime(stats.atime, stats.mtime, dest_path)
  chmod(dest_path, stats.mode, options)
end

.create_dirvoid

This method returns an undefined value.

Create directory structure

Examples:

create_directory('/path/to/dir')
tree =
  'app' => [
    'README.md',
    ['Gemfile', "gem 'tty-file'"],
    'lib' => [
      'cli.rb',
      ['file_utils.rb', "require 'tty-file'"]
    ]
    'spec' => []
  ]

create_directory(tree)

Parameters:

  • destination (String, Hash)

    the path or data structure describing directory tree



181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
# File 'lib/tty/file.rb', line 181

def create_directory(destination, *args, **options)
  parent = args.size.nonzero? ? args.pop : nil
  if destination.is_a?(String)
    destination = { destination => [] }
  end

  destination.each do |dir, files|
    path = parent.nil? ? dir : ::File.join(parent, dir)
    unless ::File.exist?(path)
      ::FileUtils.mkdir_p(path)
      log_status(:create, path, options.fetch(:verbose, true),
                                options.fetch(:color, :green))
    end

    files.each do |filename, contents|
      if filename.respond_to?(:each_pair)
        create_directory(filename, path, options)
      else
        create_file(::File.join(path, filename), contents, options)
      end
    end
  end
end

.create_directory(destination, *args, **options) ⇒ void

This method returns an undefined value.

Create directory structure

Examples:

create_directory('/path/to/dir')
tree =
  'app' => [
    'README.md',
    ['Gemfile', "gem 'tty-file'"],
    'lib' => [
      'cli.rb',
      ['file_utils.rb', "require 'tty-file'"]
    ]
    'spec' => []
  ]

create_directory(tree)

Parameters:

  • destination (String, Hash)

    the path or data structure describing directory tree



156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
# File 'lib/tty/file.rb', line 156

def create_directory(destination, *args, **options)
  parent = args.size.nonzero? ? args.pop : nil
  if destination.is_a?(String)
    destination = { destination => [] }
  end

  destination.each do |dir, files|
    path = parent.nil? ? dir : ::File.join(parent, dir)
    unless ::File.exist?(path)
      ::FileUtils.mkdir_p(path)
      log_status(:create, path, options.fetch(:verbose, true),
                                options.fetch(:color, :green))
    end

    files.each do |filename, contents|
      if filename.respond_to?(:each_pair)
        create_directory(filename, path, options)
      else
        create_file(::File.join(path, filename), contents, options)
      end
    end
  end
end

.create_file(relative_path, *args, **options, &block) ⇒ Object

Create new file if doesn’t exist

Examples:

create_file('doc/README.md', '# Title header')
create_file 'doc/README.md' do
  '# Title Header'
end

Parameters:

  • relative_path (String)
  • content (String|nil)

    the content to add to file

  • options (Hash)

Options Hash (**options):

  • :force (Symbol)

    forces ovewrite if conflict present



202
203
204
205
206
# File 'lib/tty/file.rb', line 202

def create_file(relative_path, *args, **options, &block)
  content = block_given? ? block[] : args.join

  CreateFile.new(self, relative_path, content, options).call
end

.diff(path_a, path_b, **options) ⇒ Object

Diff files line by line

Examples:

diff(file_a, file_b, format: :old)

Parameters:

  • path_a (String)
  • path_b (String)
  • options (Hash[Symbol])

Options Hash (**options):

  • :format (Symbol)

    the diffining output format

  • :context_lines (Symbol)

    the number of extra lines for the context

  • :threshold (Symbol)

    maximum file size in bytes



344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
# File 'lib/tty/file.rb', line 344

def diff(path_a, path_b, **options)
  threshold = options[:threshold] || 10_000_000
  output = []

  open_tempfile_if_missing(path_a) do |file_a|
    if ::File.size(file_a) > threshold
      raise ArgumentError, "(file size of #{file_a.path} exceeds #{threshold} bytes, diff output suppressed)"
    end
    if binary?(file_a)
      raise ArgumentError, "(#{file_a.path} is binary, diff output suppressed)"
    end
    open_tempfile_if_missing(path_b) do |file_b|
      if binary?(file_b)
        raise ArgumentError, "(#{file_a.path} is binary, diff output suppressed)"
      end
      if ::File.size(file_b) > threshold
        return "(file size of #{file_b.path} exceeds #{threshold} bytes, diff output suppressed)"
      end

      log_status(:diff, "#{file_a.path} - #{file_b.path}",
                 options.fetch(:verbose, true), options.fetch(:color, :green))
      return output.join if options[:noop]

      block_size = file_a.lstat.blksize
      while !file_a.eof? && !file_b.eof?
        output << Differ.new(file_a.read(block_size),
                             file_b.read(block_size),
                             options).call
      end
    end
  end
  output.join
end

.diff_filesObject

Diff files line by line

Examples:

diff(file_a, file_b, format: :old)

Parameters:

  • path_a (String)
  • path_b (String)
  • options (Hash[Symbol])


379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
# File 'lib/tty/file.rb', line 379

def diff(path_a, path_b, **options)
  threshold = options[:threshold] || 10_000_000
  output = []

  open_tempfile_if_missing(path_a) do |file_a|
    if ::File.size(file_a) > threshold
      raise ArgumentError, "(file size of #{file_a.path} exceeds #{threshold} bytes, diff output suppressed)"
    end
    if binary?(file_a)
      raise ArgumentError, "(#{file_a.path} is binary, diff output suppressed)"
    end
    open_tempfile_if_missing(path_b) do |file_b|
      if binary?(file_b)
        raise ArgumentError, "(#{file_a.path} is binary, diff output suppressed)"
      end
      if ::File.size(file_b) > threshold
        return "(file size of #{file_b.path} exceeds #{threshold} bytes, diff output suppressed)"
      end

      log_status(:diff, "#{file_a.path} - #{file_b.path}",
                 options.fetch(:verbose, true), options.fetch(:color, :green))
      return output.join if options[:noop]

      block_size = file_a.lstat.blksize
      while !file_a.eof? && !file_b.eof?
        output << Differ.new(file_a.read(block_size),
                             file_b.read(block_size),
                             options).call
      end
    end
  end
  output.join
end

.download_file(uri, *args, **options, &block) ⇒ Object

Download the content from a given address and save at the given relative destination. If block is provided in place of destination, the content of of the uri is yielded.

Examples:

download_file("https://gist.github.com/4701967",
              "doc/benchmarks")
download_file("https://gist.github.com/4701967") do |content|
  content.gsub("\n", " ")
end

Parameters:

  • uri (String)

    the URI address

  • dest (String)

    the relative path to save

  • options (Hash[Symbol])
  • options (Symbol)

    :limit the limit of redirects



405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
# File 'lib/tty/file.rb', line 405

def download_file(uri, *args, **options, &block)
  dest_path = args.first || ::File.basename(uri)

  unless uri =~ %r{^https?\://}
    copy_file(uri, dest_path, options)
    return
  end

  content = DownloadFile.new(uri, dest_path, options).call

  if block_given?
    content = (block.arity.nonzero? ? block[content] : block[])
  end

  create_file(dest_path, content, options)
end

.escape_glob_path(path) ⇒ String

Escape glob character in a path

Examples:

escape_glob_path("foo[bar]") => "foo\\[bar\\]"

Parameters:

  • path (String)

    the path to escape

Returns:

  • (String)


682
683
684
# File 'lib/tty/file.rb', line 682

def escape_glob_path(path)
  path.gsub(/[\\\{\}\[\]\*\?]/) { |x| "\\" + x }
end

.get_fileObject

Download the content from a given address and save at the given relative destination. If block is provided in place of destination, the content of of the uri is yielded.

Examples:

download_file("https://gist.github.com/4701967",
              "doc/benchmarks")
download_file("https://gist.github.com/4701967") do |content|
  content.gsub("\n", " ")
end

Parameters:

  • uri (String)

    the URI address

  • dest (String)

    the relative path to save

  • options (Hash[Symbol])
  • options (Symbol)

    :limit the limit of redirects



423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
# File 'lib/tty/file.rb', line 423

def download_file(uri, *args, **options, &block)
  dest_path = args.first || ::File.basename(uri)

  unless uri =~ %r{^https?\://}
    copy_file(uri, dest_path, options)
    return
  end

  content = DownloadFile.new(uri, dest_path, options).call

  if block_given?
    content = (block.arity.nonzero? ? block[content] : block[])
  end

  create_file(dest_path, content, options)
end

.gsub_fileBoolean

Replace content of a file matching string, returning false when no substitutions were performed, true otherwise.

Examples:

replace_in_file('Gemfile', /gem 'rails'/, "gem 'hanami'")
replace_in_file('Gemfile', /gem 'rails'/) do |match|
  match = "gem 'hanami'"
end

Parameters:

  • options (Hash)

    a customizable set of options

Returns:

  • (Boolean)

    true when replaced content, false otherwise



596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
# File 'lib/tty/file.rb', line 596

def replace_in_file(relative_path, *args, **options, &block)
  check_path(relative_path)
  contents = ::File.binread(relative_path)
  replacement = (block ? block[] : args[1..-1].join).gsub('\0', '')
  match = Regexp.escape(replacement)
  status = nil

  log_status(:replace, relative_path, options.fetch(:verbose, true),
                                      options.fetch(:color, :green))
  return false if options[:noop]

  if options.fetch(:force, true) || !(contents =~ /^#{match}(\r?\n)*/m)
    status = contents.gsub!(*args, &block)
    if !status.nil?
      ::File.open(relative_path, 'wb') do |file|
        file.write(contents)
      end
    end
  end
  !status.nil?
end

.inject_into_file(relative_path, *args, **options, &block) ⇒ Object

Inject content into file at a given location

Examples:

inject_into_file('Gemfile', "gem 'tty'", after: "gem 'rack'\n")
inject_into_file('Gemfile', "gem 'tty'\n", "gem 'loaf'", after: "gem 'rack'\n")
inject_into_file('Gemfile', after: "gem 'rack'\n") do
  "gem 'tty'\n"
end

Parameters:

  • relative_path (String)
  • options (Hash)

Options Hash (**options):

  • :before (Symbol)

    the matching line to insert content before

  • :after (Symbol)

    the matching line to insert content after

  • :force (Symbol)

    insert content more than once

  • :verbose (Symbol)

    log status



517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
# File 'lib/tty/file.rb', line 517

def inject_into_file(relative_path, *args, **options, &block)
  check_path(relative_path)
  replacement = block_given? ? block[] : args.join

  flag, match = if options.key?(:after)
                  [:after, options.delete(:after)]
                else
                  [:before, options.delete(:before)]
                end

  match = match.is_a?(Regexp) ? match : Regexp.escape(match)
  content = if flag == :after
              '\0' + replacement
            else
              replacement + '\0'
            end

  log_status(:inject, relative_path, options.fetch(:verbose, true),
                                     options.fetch(:color, :green))
  replace_in_file(relative_path, /#{match}/, content,
                  options.merge(verbose: false))
end

.insert_into_fileObject

Inject content into file at a given location

Examples:

inject_into_file('Gemfile', "gem 'tty'", after: "gem 'rack'\n")
inject_into_file('Gemfile', "gem 'tty'\n", "gem 'loaf'", after: "gem 'rack'\n")
inject_into_file('Gemfile', after: "gem 'rack'\n") do
  "gem 'tty'\n"
end

Parameters:

  • relative_path (String)
  • options (Hash)


541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
# File 'lib/tty/file.rb', line 541

def inject_into_file(relative_path, *args, **options, &block)
  check_path(relative_path)
  replacement = block_given? ? block[] : args.join

  flag, match = if options.key?(:after)
                  [:after, options.delete(:after)]
                else
                  [:before, options.delete(:before)]
                end

  match = match.is_a?(Regexp) ? match : Regexp.escape(match)
  content = if flag == :after
              '\0' + replacement
            else
              replacement + '\0'
            end

  log_status(:inject, relative_path, options.fetch(:verbose, true),
                                     options.fetch(:color, :green))
  replace_in_file(relative_path, /#{match}/, content,
                  options.merge(verbose: false))
end

.prepend_to_file(relative_path, *args, **options, &block) ⇒ Object

Prepend to a file

Examples:

prepend_to_file('Gemfile', "gem 'tty'")
prepend_to_file('Gemfile') do
  "gem 'tty'"
end

Parameters:

  • relative_path (String)
  • content (Array[String])

    the content to preped to file



441
442
443
444
445
446
# File 'lib/tty/file.rb', line 441

def prepend_to_file(relative_path, *args, **options, &block)
  log_status(:prepend, relative_path, options.fetch(:verbose, true),
                                      options.fetch(:color, :green))
  options.merge!(before: /\A/, verbose: false)
  inject_into_file(relative_path, *(args << options), &block)
end

.private_module_function(method) ⇒ Object



17
18
19
20
# File 'lib/tty/file.rb', line 17

def self.private_module_function(method)
  module_function(method)
  private_class_method(method)
end

.remove_file(relative_path, *args, **options) ⇒ Object

Remove a file or a directory at specified relative path.

Examples:

remove_file 'doc/README.md'

Parameters:

  • options (Hash[:Symbol])

Options Hash (**options):

  • :noop (Symbol)

    pretend removing file

  • :force (Symbol)

    remove file ignoring errors

  • :verbose (Symbol)

    log status

  • :secure (Symbol)

    for secure removing



615
616
617
618
619
620
621
622
623
# File 'lib/tty/file.rb', line 615

def remove_file(relative_path, *args, **options)
  log_status(:remove, relative_path, options.fetch(:verbose, true),
                                     options.fetch(:color, :red))

  return if options[:noop] || !::File.exist?(relative_path)

  ::FileUtils.rm_r(relative_path, force: options[:force],
                   secure: options.fetch(:secure, true))
end

.replace_in_file(relative_path, *args, **options, &block) ⇒ Boolean

Replace content of a file matching string, returning false when no substitutions were performed, true otherwise.

Examples:

replace_in_file('Gemfile', /gem 'rails'/, "gem 'hanami'")
replace_in_file('Gemfile', /gem 'rails'/) do |match|
  match = "gem 'hanami'"
end

Parameters:

  • options (Hash)

    a customizable set of options

Options Hash (**options):

  • :force (Symbol)

    replace content even if present

  • :verbose (Symbol)

    log status

Returns:

  • (Boolean)

    true when replaced content, false otherwise



573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
# File 'lib/tty/file.rb', line 573

def replace_in_file(relative_path, *args, **options, &block)
  check_path(relative_path)
  contents = ::File.binread(relative_path)
  replacement = (block ? block[] : args[1..-1].join).gsub('\0', '')
  match = Regexp.escape(replacement)
  status = nil

  log_status(:replace, relative_path, options.fetch(:verbose, true),
                                      options.fetch(:color, :green))
  return false if options[:noop]

  if options.fetch(:force, true) || !(contents =~ /^#{match}(\r?\n)*/m)
    status = contents.gsub!(*args, &block)
    if !status.nil?
      ::File.open(relative_path, 'wb') do |file|
        file.write(contents)
      end
    end
  end
  !status.nil?
end

.safe_append_to_file(relative_path, *args, **options, &block) ⇒ Object

Safely append to file checking if content is not already present



486
487
488
# File 'lib/tty/file.rb', line 486

def safe_append_to_file(relative_path, *args, **options, &block)
  append_to_file(relative_path, *args, **(options.merge(force: false)), &block)
end

.safe_inject_into_file(relative_path, *args, **options, &block) ⇒ Object

Safely prepend to file checking if content is not already present



547
548
549
# File 'lib/tty/file.rb', line 547

def safe_inject_into_file(relative_path, *args, **options, &block)
  inject_into_file(relative_path, *args, **(options.merge(force: false)), &block)
end

.safe_prepend_to_file(relative_path, *args, **options, &block) ⇒ Object

Safely prepend to file checking if content is not already present



452
453
454
# File 'lib/tty/file.rb', line 452

def safe_prepend_to_file(relative_path, *args, **options, &block)
  prepend_to_file(relative_path, *args, **(options.merge(force: false)), &block)
end

.tail_file(relative_path, num_lines = 10, **options, &block) ⇒ Array[String]

Provide the last number of lines from a file

Examples:

tail_file 'filename'
# =>  ['line 19', 'line20', ... ]
tail_file 'filename', 15
# =>  ['line 19', 'line20', ... ]

Parameters:

  • relative_path (String)

    the relative path to a file

  • num_lines (Integer) (defaults to: 10)

    the number of lines to return from file

Returns:

  • (Array[String])


645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
# File 'lib/tty/file.rb', line 645

def tail_file(relative_path, num_lines = 10, **options, &block)
  file       = ::File.open(relative_path)
  chunk_size = options.fetch(:chunk_size, 512)
  line_sep   = $/
  lines      = []
  newline_count = 0

  ReadBackwardFile.new(file, chunk_size).each_chunk do |chunk|
    # look for newline index counting from right of chunk
    while (nl_index = chunk.rindex(line_sep, (nl_index || chunk.size) - 1))
      newline_count += 1
      break if newline_count > num_lines || nl_index.zero?
    end

    if newline_count > num_lines
      lines.insert(0, chunk[(nl_index + 1)..-1])
      break
    else
      lines.insert(0, chunk)
    end
  end

  lines.join.split(line_sep).each(&block).to_a
end

Instance Method Details

#check_path(path) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Check if path exists

Parameters:

  • path (String)

Raises:

  • (ArgumentError)


694
695
696
697
# File 'lib/tty/file.rb', line 694

def check_path(path)
  return if ::File.exist?(path)
  raise InvalidPathError, "File path \"#{path}\" does not exist."
end

#decorate(message, color) ⇒ Object



703
704
705
# File 'lib/tty/file.rb', line 703

def decorate(message, color)
  @pastel.send(color, message)
end

#log_status(cmd, message, verbose, color = false) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Log file operation



711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
# File 'lib/tty/file.rb', line 711

def log_status(cmd, message, verbose, color = false)
  return unless verbose

  cmd = cmd.to_s.rjust(12)
  if color
    i = cmd.index(/[a-z]/)
    cmd = cmd[0...i] + decorate(cmd[i..-1], color)
  end

  message = "#{cmd}  #{message}"
  message += "\n" unless message.end_with?("\n")

  @output.print(message)
  @output.flush
end

#open_tempfile_if_missing(object, &block) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

If content is not a path to a file, create a tempfile and open it instead.

Parameters:

  • object (String)

    a path to file or content



735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
# File 'lib/tty/file.rb', line 735

def open_tempfile_if_missing(object, &block)
  if ::FileTest.file?(object)
    ::File.open(object, &block)
  else
    tempfile = Tempfile.new('tty-file-diff')
    tempfile << object
    tempfile.rewind

    block[tempfile]

    unless tempfile.nil?
      tempfile.close
      tempfile.unlink
    end
  end
end