Class Yax::Session
In: nist/yax.rb
Parent: Object
Session Yax Module: Yax

Represents an environment in which one can script an interaction with a process (others should be possible, but only bash has been tested).

For an overview of use, features, and an example, see ReadMe.txt.

Methods

External Aliases

default_maxSeconds -> time_out
default_maxSeconds= -> time_out=

Attributes

cd_max_seconds  [RW]  Session’s file operations other than cd are thin wrappers on FileUtil, that make logging consistent, but which do not have time limits. cd is different because it needs to invoke both "cd" using command, and the FileUtil version (so that tests like File.exist? and File.directory? work). If we don’t assign a time limit to "command cd", the subsequent operation will apply one of it’s own. So we need to define a limit for cd.
default_maxSeconds  [RW]  Specifies the maximum time that expect and finish will wait, if the script does not supply a time.
dir_hash  [RW]  @dir_hash lets you assign symbolic names to directories @dir_hash has:
  • key is a Symbol
  • value is an absolute path to a directory
dir_overide  [RW]  @dir_overide lets you override the name of directory resulting from decompression of an archive. @dir_overide is a Hash with:
  • key is a string URL basename without extension
  • value is a directory name.
error_log_path  [RW]  @error_log_path contains a required absolute path to the error log file. Each command replaces this file: if you want the errors for the entire Session, consult the transcript.
exit_status  [RW]  The exit_status is an integer returned by most recently finished command: 0 is success.
exit_status_path  [RW]  @exit_status_path contains a required absolute path to a file that’s used to record command exit statuses.
give_finishing_notice  [RW]  If true, provides extra debug information at the price of excessive transcript verbosity.
log_prompt  [RW]  If true, prompts are logged like other output
password  [RW]  The automatic response to @password_prompt
password_prompt  [RW]  A String or Regex used to decide when an administrative password is required (such as when a script or a command uses sudo). If this is nil, Session will not attempt to detect and answer administative passwords. If a password is actually demanded, your script will hang until the operation times out.
pattern_hash_class  [RW]  To accomodate multiple possible outcomes, expect can take a Hash argument. In many cases, however, a String or Regex good enough to specify the next response from the spawned process. In that case, @pattern_hash_class is instantiated, containing the expected String or Regex.
pid  [RW]  The process ID of the spawned process
prefixes  [RW]  A Hash used to specify the prefixes that identify lines in the transcript.
prompt  [RW]  A String or Regexp describing the prompt issued by the spawned process. You may need to change this if you:
  • spawn a process other than bash
  • don’t use OS X
  • customize your shell

Do not confuse this attribute with @password_prompt.

pty_workaround  [RW]  When set to true, Session attempts to work around some PTY idiosyncrasies
stdin  [RW]  IO that the spawned process takes input from.
stdout  [RW]  IO that the spawned process writes to.
time_log_path  [RW]  @time_log_path is optional. If present, a log of execution times will be kept.
time_log_reset  [RW]  If @time_log_reset is true, the previous time log (if any) will be removed when each session is spawned. Otherwise a single log will be used across sessions.
time_stamp_banners  [RW]  Turning off timestamps is nice to keep regression test results date independent.
timeout_multiplier  [RW]  Scripts should express time limits as measurements made under a particular set of conditions. You can then set the @timeout_multiplier to increase or decrease time limits according to the new hardware. The @timeout_offset is a minimal time added to every time limit (after multiplication by @timeout_multiplier)
timeout_offset  [RW]  Used to scale timeouts: see @timeout_multiplier
transcript  [RW]  The @trascript records the session for debug purposes. When @transcript is not nil, it must respond to <<. If it also responds to flush, each log entry will be flushed.
url_hash  [RW]  @url_hash lets you assign symbolic names to URLs @url_hash has:
  • key is a Symbol
  • value is a URL

Public Class methods

Specifies the default value of the prompt attribute. This returns the default pattern that cmd will wait for. This is user dependent. Possible improvements:

  • include the host name
  • include the current working directory.

Tested only under OS X, where the prompt for root ends with # instead of $ The root prompt is used if the script is invoked with sudo TBD: there is probably a better way to get this from the OS, rather than guessing it.

new does not make the instance usable: it needs to spawn first. After you create an instance you can tweak its attributes before spawning.

Spawn a new process, executing the indicated program, and create a new instance that communicates with the process. Use new instead if you want to adjust the attributes.

Public Instance methods

answer(response)

Alias for respond

Examines the extension of a file name or URL to determine the type of archive. Returns a two element array containing:

      result[0] = the extension
      result[1] = gnutar decompression option

Display a banner on both the console and the transcript. The banner contains the specified text. It may also have a timestamp (if @time_stamp_banners is true).

Constructs @dir_hash from @url_hash

Set the working directory (both the shell’s via :command, and Ruby via FileUtils::cd) to a specified value. Several types of argument are acceptable:

  • ’-’ which returns to the previous directory
  • A String path (relative or absolute)
  • A Symbol previously associated with a path in dir_hash

dir_hash is setup by

  • cd! which you invoke at your discretion
  • build_default_dir_hash, which is called by :prepare during :spawn. This method adds to dir_hash keys that are present in url_hash, but missing from dir_hash. The values are derived by dirName.

This method can be fed an optional block. The new directory is set before the block executes, and the original directory is restored after the block has finished. The previous_directory is also restored, so that a subsequent "cd ’-’" takes you to the directory before this method executed (instead of the one specified here).

Unlike the bash command, this takes any number of arguments which it assembles with the appropriate separator into a single path. Also unlike bash, it raises an exception if the argument does not correspond to a reachable directory.

Associate a directory with nameSymbol, so that you can go there using ‘cd nameSymbol’. Does not change the current directory. directory can be absolute or relative. If it is relative, it is made absolute based on the current working directory.

Change permissions

cmd(command, maxSeconds=nil, silentlyIgnoreNonzeroExitStatus=false)

Alias for command

Return a Boolean, true if files have identical contents.

Send a string to the spawned process. If maxSeconds is specified, the command will block until finished. If maxSedonds is not specified, or nil, you can :expect and :reply. Each invocation rewrites the error log (which is copied to transcript).

Copies a file(s) src to dest. If dest is a directory, copies src to dest/src. src can be a list or a directory: unlike bash, you don’t need a -r for directories. Also unlike bash (but like FileUtils::cp_r) you use ’.’ as a wildcard instead of ’*’ when you want to copy all files in directory.

Download the file specified by the given URL or symbolic name (if it has not already been downloaded). You need to have curl installed.

Similar to resolve_dir, but further processes String inputs to remove the extension and the leading path. Similar to dirName, but accepts Array inputs, and attempts to look up dir in dir_hash. Returns a local directory.

Guesses where to put the error log

Guesses where to put the error status collection file.

Instance side behavior of class method with same name.

Guesses where to put the time log.

Attempts to kill the pocess with SIGTERM. If the process has not terminated by maxSeconds, follows up with SIGKILL.

Given a symoblic name of an entry in url_hash, or an URL that points to a .tgz or .tar.gz file, return the relative directory expected to result from untgz, by removing the extension and the path leading up to the file name. Return this result, unless it is a key into dir_override, in which case the corresponding value is returned. If an overide is specified in dir_overide, that is used instead.

Sets the named environmental variable for use during the session, optionally warning the user to make a more permanent setting. If warn is false, the user is not asked to make any changes. This is useful for settings that are necessary only for compilation.

If forceValue is false, any previously value is acceptable, so an existing value is not changed. In this case the user is not asked to do anything unless the value is undefined.

If forceValue is true, only the provided value is acceptable. The environmental variable will be changed if necessary. If it is changed, and warning==true, the user is advised change the value.

If value is nil, the environmental variable is unset. In this case forceValue and warning have no effect.

Returns the final value of the named environmental variable. (an empty String if the value is unset).

Note that OS X is smart enough to give you access to these when you sudo. You can readily prove this by executing in a bash shell ‘export AnswerToEverything=42’ and then executing ‘sudo echo $AnswerToEverything‘

Sets the named environmental path variable to include value (for use during the session), optionally warning the user to make a more permanent setting.

If the path is not defined at all, this will define it. If the path is defined, and contains value, nothing happens. If the path is defined but does not contain value,this prefixes value onto the path.

Expect the spawned process to produce some output. pat can be a String, a Regexp, or a Hash (keys identify patterns, values are Strings or Regexp). Raises an exception if no match occurs, unless silentlyContinueAfterTimeout is true. If a match does occur, returns an Array:

      result[0]=key for pattern that matched (:expected if pat is a String or Regexp)
      result[1]=match result

Similar to resolve_file, but further processes String inputs to remove the leading path. Similar to fileName, but accepts Array inputs. Returns a local directory.

Given a symbolic name of an entry in url_hash, or an URL that refers to a file, return the relative name of the file, by removing the path leading up to the file name, but keeping the extension.

Finish executing the most recent command. If this has already been called since the most recent command started, does nothing. Otherwise it blocks until the shell issues a prompt. You usually don’t need to explicitly call this, because it’s done automatically. When a command has maxSeconds, this is called automatically. When a command does not have maxSeconds (so that expect can be called), the subsequent command will call this before issuing itself to the shell. If you ask the shell to die, it will also call this (in case the previous command was called without maxSeconds).

Prompts the user for password and saves it in the @passsword attribute, in order to provide it to ‘sudo’.

Given a scaled time, return an unscaled time. This is the inverse of scaled_seconds

Send a signal to the spawned process. ‘SIGTERM’ is polite, but not guaranteed to stop the process. ‘SIGKILL’ is guaranteed to stop the process

Execute block under a time limit (which gets scaled).

Creates a hard link new which points to old. If new already exists and it is a directory, creates a symbolic link new/old

Creates a symbolic link new which points to old. If new already exists and it is a directory, creates a symbolic link new/old. If new already exists and is a link, replaces it.

Write a string onto the @transcript. The string can take optional arguments along the lines of printf. A prefix that describes the type of string is applied.

Log some output from the spawned process.

Logs execution time of block, if @time_log_path is specified. Without @time_log_path, executes block without timing it. In either case, returns the block result.

Load the input file into memory, make the specified changes, and write the modified file to output. If output is nil, replace the input file. Changes is a hash: keys are String or Regexp patterns to be globally replaced, values are String replacement values.

Creates one or more directories (including any necessary parent directories)

Moves file(s) src to dest. If file and dest exist on the different disk partition, the file is copied instead. Unlike cp, the src argument does not accept ’.’ wilcards (or ’*’ for that matter).

Ensure that file paths are absolute. This is necessary so that these files can be found after a cd.

Write a notice to @transcript. The string can take optional arguments along the lines of printf.

PHB knows the directory structure of Amber projects, so when PHB is available, various temp files can be placed in more appropriate directories.

reply(response)

Alias for respond

If input is:

  • A Symbol, a directory is looked up in dir_hash
  • A String, it is returned unchanged
  • An Array, each element is recursively resolved

Raises an exception if a symbolic name does not have a corresponding value, unless silent is true.

If input is:

  • A Symbol, a file is computed from the corresponding value in url_hash
  • A String, it is returned unchanged
  • An Array, each element is recursively resolved

Raises an exception if a symbolic name does not have a corresponding value, unless silent is true.

If input is:

  • A Symbol, return a URL by lookup in url_hash
  • A String, return the input
  • An Array, each element is recursively resolved

Raises an exception if a symbolic name does not have a corresponding value, unless silent is true.

Send a string to the spawned process

Remove files and directories named in list.

Given an unscaled time limit, scale it to make it appropriate for the current hardware.

snd(response)

Alias for respond

Spawn a new process, executing the indicated program. Once command has terminated, send, expect, and command will misbehave. You can, of course, spawn again. This has only been tested with bash!

Compress the specified directory into an archive. The extension determines the compression type, and is used to derive the name of the resulting file. Instead of just specifying the extension, you can pass an entire sample filename to extension, and this method will extract the file name suffix and the compression type to use (throwing away the base name).

Empties the time log (if any)

Decompress the archive specifed by the given URL or symbolic name. Does not download the archive, just decompresses it. Can handle: .tgz, .tar.gz, .tar.bz2

Wait for the spawned process to terminate on its own.

[Validate]