alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

Scala example source code file (FileCompletion.scala)

This example Scala source code file (FileCompletion.scala) is included in the DevDaily.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Java by Example" TM.

Java - Scala tags/keywords

directory, filecompletion, list, list, nil, nil, option, path, path, some, string, string

The Scala FileCompletion.scala source code

/* NSC -- new Scala compiler
 * Copyright 2005-2011 LAMP/EPFL
 * @author Paul Phillips
 */
 
package scala.tools.nsc
package interpreter

/** TODO
 *  Spaces, dots, and other things in filenames are not correctly handled.
 *  space-escaping, knowing when we're inside quotes, etc. would be nice.
 */

import io.{ Directory, Path }

/** This isn't 100% clean right now, but it works and is simple.  Rather
 *  than delegate to new objects on each '/' in the path, we treat the
 *  buffer like a path and process it directly.
 */
object FileCompletion {  
  def executionFor(buffer: String): Option[Path] = {
    Some(Directory.Home match {
      case Some(d) if buffer startsWith "~" => d / buffer.tail
      case _                                => Path(buffer)
    }) filter (_.exists)
  }

  private def fileCompletionForwarder(buffer: String, where: Directory): List[String] = {
    completionsFor(where.path + buffer) map (_ stripPrefix where.path) toList
  }
  
  private def homeCompletions(buffer: String): List[String] = {
    require(buffer startsWith "~/")
    val home = Directory.Home getOrElse (return Nil)
    fileCompletionForwarder(buffer.tail, home) map ("~" + _)
  }
  private def cwdCompletions(buffer: String): List[String] = {
    require(buffer startsWith "./")
    val cwd = Directory.Current getOrElse (return Nil)
    fileCompletionForwarder(buffer.tail, cwd) map ("." + _)
  }
  
  def completionsFor(buffer: String): List[String] =
    if (buffer startsWith "~/") homeCompletions(buffer)
    else if (buffer startsWith "./") cwdCompletions(buffer)
    else {
      val p = Path(buffer)
      val (dir, stub) =
        // don't want /foo/. expanding "."
        if (p.name == ".") (p.parent, ".")
        else if (p.isDirectory) (p.toDirectory, "")
        else (p.parent, p.name)

      dir.list filter (_.name startsWith stub) map (_.path) toList
    }
}

Other Scala examples (source code examples)

Here is a short list of links related to this Scala FileCompletion.scala source code file:

... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.