<commit_before>var fs = require('fs')
var level = require('level')
var encoding = require('dat-encoding')

module.exports = function getDb (dat, cb) {
  if (!dat.db) {
    try {
      fs.accessSync(dat.datPath, fs.F_OK)
    } catch (e) { fs.mkdirSync(dat.datPath) }
  }
  var db = dat.db = dat.db || level(dat.datPath)
  tryResume()

  function tryResume () {
    if (dat.port) db.put('!dat!port', dat.port)
    db.get('!dat!key', function (err, value) {
      if (err && !err.notFound) return cb(err)
      if (!value) return cb(null, db)
      if (dat.key && dat.key.toString('hex') !== value) return cb('Another Dat was already downloaded here.')

      value = encoding.decode(value)
      dat.key = value
      dat.resume = true

      if (dat.port) return cb(null) // Port set in opts
      db.get('!dat!port', function (err, portVal) {
        if (err && !err.notFound) return cb(err)
        if (portVal) dat.port = portVal
        cb(null)
      })
    })
  }
}<commit_msg>only require level when no db is specified<commit_after>var fs = require('fs')
var encoding = require('dat-encoding')

module.exports = function getDb (dat, cb) {
  if (!dat.db) {
    try {
      fs.accessSync(dat.datPath, fs.F_OK)
    } catch (e) { fs.mkdirSync(dat.datPath) }
    dat.db = require('level')(dat.datPath)
  }
  tryResume()

  function tryResume () {
    var db = dat.db
    if (dat.port) db.put('!dat!port', dat.port)
    db.get('!dat!key', function (err, value) {
      if (err && !err.notFound) return cb(err)
      if (!value) return cb(null, db)
      if (dat.key && dat.key.toString('hex') !== value) return cb('Another Dat was already downloaded here.')

      value = encoding.decode(value)
      dat.key = value
      dat.resume = true

      if (dat.port) return cb(null) // Port set in opts
      db.get('!dat!port', function (err, portVal) {
        if (err && !err.notFound) return cb(err)
        if (portVal) dat.port = portVal
        cb(null)
      })
    })
  }
}
{'fraction_non_alphanumeric': 0.16329625884732052, 'fraction_numerical': 0.0, 'mean_word_length': 2.6580406654343807, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '587251', 'n_tokens_mistral': 700, 'n_tokens_neox': 688, 'n_words': 178}