Class: LENSE

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

Constant Summary collapse

VERSION =
'0.2.13'
LENSE_DIR =
File.join(ENV['HOME'],'.lense')
COURSES_DIR =
File.join(LENSE_DIR,'courses')
CURRENT_COURSE_FILE =
File.join(LENSE_DIR,'current_course')
LOCAL_LENSE_DIR =
File.join(ENV['PWD'],'.lense')
DEPS_DIR =
File.join(LOCAL_LENSE_DIR,'deps')
REFS_DIR =
File.join(LOCAL_LENSE_DIR,'refs')
CURRENT_REF_FILE =
File.join(REFS_DIR,'current')
LENSE_FILE =
File.join(ENV['PWD'],'LENSEfile')
API_BASE =
'http://lightweightnetsec.com'
TARFLAGS =
''

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeLENSE

Returns a new instance of LENSE.



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/lense.rb', line 22

def initialize()
  Dir.mkdir(LENSE_DIR) unless File.directory?(LENSE_DIR)
  Dir.mkdir(COURSES_DIR) unless File.directory?(COURSES_DIR)
  File.open(CURRENT_COURSE_FILE, 'w') {} unless File.file?(CURRENT_COURSE_FILE)

  config_file = File.join(LENSE_DIR,'config')
  config_str = File.file?(config_file) ? File.read(config_file) : ''

  @config = Psych.load(config_str) || {}

  @current_course = File.read(CURRENT_COURSE_FILE).strip()
  @current_course = '> NOT SET <' if @current_course.empty?
  @lense_file_hash = hash_file(LENSE_FILE) if File.file?(LENSE_FILE)
  @DB = SQLite3::Database.new File.join(LOCAL_LENSE_DIR,'db') if File.file? File.join(LOCAL_LENSE_DIR,'db')
end

Instance Attribute Details

#configObject (readonly)

Returns the value of attribute config.



8
9
10
# File 'lib/lense.rb', line 8

def config
  @config
end

#current_courseObject (readonly)

Returns the value of attribute current_course.



8
9
10
# File 'lib/lense.rb', line 8

def current_course
  @current_course
end

#lense_file_hashObject (readonly)

Returns the value of attribute lense_file_hash.



8
9
10
# File 'lib/lense.rb', line 8

def lense_file_hash
  @lense_file_hash
end

Instance Method Details

#clone(repo) ⇒ Object



281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
# File 'lib/lense.rb', line 281

def clone(repo)
  exit_now!("Invalid repo name.") unless repo =~ /\A\w+\/\w+\Z/
  username, project_name = repo.split '/'

  say "making dirs ..."
  # make repo dir in current directory
  Dir.mkdir project_name unless File.directory? project_name

  # cd into project dir
  Dir.chdir project_name

  # make .lense dir and .lense/temp
  proj_lense_dir = '.lense'
  Dir.mkdir proj_lense_dir unless File.directory? proj_lense_dir

  temp_dir = File.join proj_lense_dir, 'temp'
  Dir.mkdir temp_dir unless File.directory? temp_dir

  # write repository name
  repo_file = File.join proj_lense_dir, 'repository'
  File.open(repo_file, 'w') { |f| f.write repo } unless File.file? repo_file

  install_repo repo, 'clone'
end

#commit(msg) ⇒ Object



168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
# File 'lib/lense.rb', line 168

def commit(msg)
  # check that we have items in staging
  rows = @DB.execute 'select path from staging;'
  rows.map! do |r|
    path = r[0]
    {
      path: path,
      hash: hash_file(path)
    }
  end

  files = rows.select do |file|
    dependency = get_dependency(file[:path])
    dependency.nil? || dependency[:file_hash] != file[:hash]
  end

  combined_hash = files.map {|f| f[:hash]}.join ''
  commit_hash = hash_contents "#{DateTime.now.to_s}#{combined_hash}"
  @DB.execute 'insert into commits (hash,message,created_at) values (?,?,?);',[commit_hash,msg,DateTime.now.to_s]
  commit_id = @DB.last_insert_row_id

  files.each do |file|
    @DB.transaction
    dependency = get_dependency(file[:path])
    if dependency.nil?
      @DB.execute 'insert into dependencies (path,added_at) values (?,?);',[file[:path],DateTime.now.to_s]
      dependency_id = @DB.last_insert_row_id
    else
      dependency_id = dependency[:id]
    end
    @DB.execute 'insert into revisions (commit_id,dependency_id,hash,created_at) values (?,?,?,?);',[commit_id,dependency_id,file[:hash],DateTime.now.to_s]
    @DB.commit
  end
  @DB.transaction
  @DB.execute 'delete from staging;'
  @DB.commit
  # add new files to dependancies
  # create a hash for the commit and add to commits
  # for all dependancies add current hashes to revisions
  # truncate staging
end

#downObject



264
265
266
267
268
269
270
# File 'lib/lense.rb', line 264

def down
  lense = read_lensefile
  lense['down'].each do |cmd|
    say "running: #{cmd}"
    `#{cmd}`
  end
end

#get_commit_logObject



248
249
250
251
252
253
254
# File 'lib/lense.rb', line 248

def get_commit_log()
  rows = @DB.execute 'select id, message, hash, created_at from commits order by created_at desc;'
  rows.each do |row|
    id, message, hash, created_at = row
    say "<%= color('#{id}',:blue) %> | #{created_at} | <%= color('#{hash}',:green) %> | #{message}"
  end
end

#initObject



117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
# File 'lib/lense.rb', line 117

def init()
  Dir.mkdir(LOCAL_LENSE_DIR) unless File.directory?(LOCAL_LENSE_DIR)
  Dir.mkdir(DEPS_DIR) unless File.directory?(DEPS_DIR)
  Dir.mkdir(REFS_DIR) unless File.directory?(REFS_DIR)
  File.open(CURRENT_REF_FILE, 'w') {} unless File.file?(CURRENT_REF_FILE)
  unless File.file?(LENSE_FILE)
    File.open(LENSE_FILE,'w') do |file|
      file.puts "---"
      file.puts "title: Uninitialized Project"
      file.puts "difficulty:"
      file.puts "authors: []"
      file.puts "dependencies: []"
      file.puts "up:"
      file.puts " - echo 'Hello'"
      file.puts "down:"
      file.puts " - echo 'Goodbye!'"
      file.puts "lesson_plan: []"
    end
    say "Created template LENSEfile"
  end
  setup_db()
end

#install_repo(repo, action) ⇒ Object



306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
# File 'lib/lense.rb', line 306

def install_repo(repo,action)
  say "making rest call"
  response = RestClient.get "#{API_BASE}/#{repo}/#{action.to_s}", { params: { format: 'json' } }
  repository = JSON.parse(response)

  # reading and checking tar file
  tar_str = Base64::decode64 repository["tar_file_base64"]
  tar_hash = repository["tar_file_fingerprint"]
  say "tar hash #{tar_hash}"

  exit_now!("Failed download. Hash does not match.") unless hash_contents(tar_str) == tar_hash

  tar_fname = "#{tar_hash}.tar"
  say "writing tar file ... #{tar_fname}"

  rel_tar_path = File.join '.lense', 'temp', tar_fname
  File.open(rel_tar_path, 'w') { |f| f.write tar_str }

  # untar
  say "untaring to ... #{rel_tar_path}"
  `tar -x#{TARFLAGS}f #{rel_tar_path}`

  say "done"
  # read lensefile
  # iterate over dependencies
  # - download
  # - verify w/ hash
end

#list_coursesObject



52
53
54
55
56
57
58
59
# File 'lib/lense.rb', line 52

def list_courses()
  puts "Installed courses ..."
  Dir.entries(COURSES_DIR).each do |c|
    prefix = c == @current_course ? " > " : "   "
    puts "#{prefix}#{c}" unless ['.','..'].include? c
  end
  puts "> Indicates current course"
end

#pullObject



276
277
278
279
# File 'lib/lense.rb', line 276

def pull()
  repo = validate_in_repo
  install_repo repo, 'pull'
end

#push(repo) ⇒ Object



272
273
274
# File 'lib/lense.rb', line 272

def push(repo)
  repo = validate_in_repo
end

#remove(file) ⇒ Object



245
246
# File 'lib/lense.rb', line 245

def remove(file)
end

#runObject



75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/lense.rb', line 75

def run()
  q_prefix = '<%= color("Q? ",:red) %>'
  hint_prefix = '<%= color("Hint: ",:yellow) %>'
  say_prefix = '<%= color("% ",:blue) %>'
  answer_prefix = '<%= color("Ans: ",:red) %>'
  question_separator = '<%= color("---",:green) %>'

  test_file = 'data/mfwvl1.yaml'
  test_str = File.file?(test_file) ? File.read(test_file) : ''
  lense_file = Psych.load(test_str) || {}

  lense_file['lesson_plan'].each do |lesson|
    say question_separator
    say "#{say_prefix} #{lesson['say']}" if lesson['say']

    if lesson['question'] && lesson['question']['ask']
      asked, hint_limit, max_asked, correct  = 0, 3, 5, false

      until correct || asked >= max_asked do
        asked += 1
        question = lesson['question']['ask']
        hint = lesson['question'] && lesson['question']['hint']

        show_hint = ''
        if hint && asked > hint_limit
          show_hint = "\n#{hint_prefix} #{hint}"
        end

        attempt = "(Attempt #{asked} of #{max_asked})"
        response = ask "#{q_prefix} #{question} #{attempt}#{show_hint}"
        correct = response == lesson['question']['expect']
      end

      if correct
        say "<%= color('Correct!',:green) %>"
      else
        say "#{answer_prefix} #{lesson['question']['expect']}"
      end
    end
  end
end

#search(term) ⇒ Object



61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/lense.rb', line 61

def search(term)
  puts "Searching course repository ..."
  response = RestClient.get "#{API_BASE}/lessons", { params: { format: 'json', text: term } }
  courses = JSON.parse(response)
  courses.each do |c|
    puts "---"
    puts "Title: #{c['title']}"
    puts "Description: #{c['description']}"
    print "Difficulty: "
    c['difficulty'].times { print '*' }
    puts ""
  end
end

#select_course(course) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/lense.rb', line 38

def select_course(course)
  courses = Dir.entries(COURSES_DIR)
  course_available = courses.include? course

  if course_available && course != @current_course
    File.open(CURRENT_COURSE_FILE, 'w') { |f| f.write course }
    course
  elsif course == @current_course
    nil
  else
    raise "Cannot find course (#{course})"
  end
end

#stage(file) ⇒ Object



210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
# File 'lib/lense.rb', line 210

def stage(file)
  if File.file?(file)
    dependency = get_dependency(file)
    if dependency.nil?
      should_stage = true
    else
      current_hash = hash_file(file)

      # is it modified?
      if dependency[:file_hash] == current_hash
        should_stage = false
      else
        should_stage = true
      end
    end

    if should_stage
      begin
        @DB.transaction
        @DB.execute "insert into staging (path) values (?);", file
        @DB.commit
      rescue
      end
    end
  end
end

#statusObject



140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
# File 'lib/lense.rb', line 140

def status()
  #say "Hash : #{@lense_file_hash}"
  exit_now!("Not a LENSE project: .lense") unless File.directory?(LOCAL_LENSE_DIR)

  say "Staged Files:\n"
  @DB.execute("select path from staging;").each do |row|
    path = row[0]
    dependency = get_dependency(path)
    action = dependency.nil? ? 'New File' : 'Modified'
    say "\t<%= color('#{action}: #{path}',:green) %>"
  end

  rows = @DB.execute 'select path from dependencies where not deleted;'
  if rows.length >0
    say "\nUnstaged Modified Files:\n"
    rows.each do |row|
      path = row[0]
      say "\t<%= color('Modified: #{path}',:red) %>"
    end
  end

  # check changes in depenancy files
  # - for each depenceny
  # - - get the current file hash
  # - - check against .lense/deps/#{rel_path_to_dep}
  # - - output any ones that have changed
end

#unstage(file) ⇒ Object



237
238
239
240
241
242
243
# File 'lib/lense.rb', line 237

def unstage(file)
  if File.file?(file)
    @DB.transaction
    @DB.execute "delete from staging where path = ?;", file
    @DB.commit
  end
end

#upObject



256
257
258
259
260
261
262
# File 'lib/lense.rb', line 256

def up
  lense = read_lensefile
  lense['up'].each do |cmd|
    say "running: #{cmd}"
    `#{cmd}`
  end
end