Class: Toys::Completion::FileSystem

Inherits:
Base
  • Object
show all
Defined in:
lib/toys/completion.rb

Overview

A Completion that returns candidates from the local file system.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(cwd: nil, omit_files: false, omit_directories: false, prefix_constraint: "") ⇒ FileSystem

Create a completion that gets candidates from names in the local file system.

Parameters:

  • cwd (String) (defaults to: nil)

    Working directory (defaults to the current dir).

  • omit_files (Boolean) (defaults to: false)

    Omit files from candidates

  • omit_directories (Boolean) (defaults to: false)

    Omit directories from candidates

  • prefix_constraint (String, Regexp) (defaults to: "")

    Constraint on the fragment prefix. Defaults to requiring the prefix be empty.



246
247
248
249
250
251
252
# File 'lib/toys/completion.rb', line 246

def initialize(cwd: nil, omit_files: false, omit_directories: false, prefix_constraint: "")
  super()
  @cwd = cwd || ::Dir.pwd
  @include_files = !omit_files
  @include_directories = !omit_directories
  @prefix_constraint = prefix_constraint
end

Instance Attribute Details

#cwdString (readonly)

Path to the starting directory.

Returns:

  • (String)


276
277
278
# File 'lib/toys/completion.rb', line 276

def cwd
  @cwd
end

#include_directoriesBoolean (readonly)

Whether directories are included in the completion candidates.

Returns:

  • (Boolean)


264
265
266
# File 'lib/toys/completion.rb', line 264

def include_directories
  @include_directories
end

#include_filesBoolean (readonly)

Whether files are included in the completion candidates.

Returns:

  • (Boolean)


258
259
260
# File 'lib/toys/completion.rb', line 258

def include_files
  @include_files
end

#prefix_constraintString, Regexp (readonly)

Constraint on the fragment prefix.

Returns:

  • (String, Regexp)


270
271
272
# File 'lib/toys/completion.rb', line 270

def prefix_constraint
  @prefix_constraint
end

Instance Method Details

#call(context) ⇒ Array<Toys::Completion::Candidate>

Returns candidates for the current completion.

Parameters:

Returns:



285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
# File 'lib/toys/completion.rb', line 285

def call(context)
  return [] unless @prefix_constraint === context.fragment_prefix
  substring = context.fragment
  prefix, name =
    if substring.empty? || substring.end_with?("/")
      [substring, ""]
    else
      ::File.split(substring)
    end
  dir = ::File.expand_path(prefix, @cwd)
  return [] unless ::File.directory?(dir)
  prefix = nil if [".", ""].include?(prefix)
  omits = [".", "..", ""]
  children = Compat.glob_in_dir(name, dir).find_all do |child|
    !omits.include?(child)
  end
  children += ::Dir.entries(dir).find_all do |child|
    child.start_with?(name) && !omits.include?(child)
  end
  generate_candidates(children.uniq.sort, prefix, dir)
end