Class: Palimpsest::Utility

Inherits:
Object
  • Object
show all
Defined in:
lib/palimpsest/utility.rb

Overview

Utility functions for Palimpsest.

Class Method Summary collapse

Class Method Details

.extract_repo(repo, treeish, directory) ⇒ Object

Extracts a git repo to a directory.

Parameters:

  • repo (Grit::Repo)
  • treeish (String)
  • directory (String)


51
52
53
54
# File 'lib/palimpsest/utility.rb', line 51

def self.extract_repo repo, treeish, directory
  input = Archive::Tar::Minitar::Input.new StringIO.new(repo.archive_tar treeish)
  input.each { |e| input.extract_entry directory, e }
end

.make_random_directory(root, prefix, dir = nil) ⇒ String

Make a random directory.

Parameters:

  • root (String)

    directory to place random directory

  • prefix (String)

    prepended to random directory name

  • dir (String, nil) (defaults to: nil)

    the random directory name (used recursively)

Returns:

  • (String)

    path to created random directory



13
14
15
16
17
18
19
20
# File 'lib/palimpsest/utility.rb', line 13

def self.make_random_directory root, prefix, dir = nil
  path = "#{root}/#{prefix}#{dir}" unless dir.nil?
  if path.nil? or File.exists? path
    make_random_directory root, prefix, Random.rand(10000000)
  else
    FileUtils.mkdir(path).first
  end
end

.safe_path?(path) ⇒ Boolean

Forbids use of ../ and ~/ in path. Forbids absolute paths.

Parameters:

  • path (String)

Returns:

  • (Boolean)


26
27
28
29
30
31
32
# File 'lib/palimpsest/utility.rb', line 26

def self.safe_path? path
  case
  when path[/(\.\.\/|~\/)/] then return false
  when path[/^\//] then return false
  else return true
  end
end

.validate_path(path, root = '') ⇒ String

Checks that a path is really rooted under a given root directory. Forbids use of ../ and ~/ in path.

Parameters:

  • path (String)
  • root (String) (defaults to: '')

    directory where path should be rooted under

Returns:

  • (String)

    input path if valid



39
40
41
42
43
44
45
# File 'lib/palimpsest/utility.rb', line 39

def self.validate_path path, root=''
  case
  when path[/(\.\.\/|~\/)/] then fail RuntimeError
  when File.expand_path(path, root)[/^#{root}/].nil? then fail RuntimeError
  else path
  end
end

.write(contents, file, preserve: false) ⇒ Object

Write contents to file.

Parameters:

  • contents (String)
  • file (String)


59
60
61
62
63
# File 'lib/palimpsest/utility.rb', line 59

def self.write contents, file, preserve: false
  original_time = File.mtime file if preserve
  File.open(file, 'w') { |f| f.write contents }
  File.utime original_time, original_time, file if preserve
end