« get me outta code hell

tempdir.js - mtui - Music Text User Interface - user-friendly command line music player
about summary refs log tree commit diff
path: root/tempdir.js
blob: 9264ffd6efc3ab0127e0a72b3cd995715870ce3e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import {mkdirSync, readdirSync, statSync} from 'node:fs'
import * as os from 'node:os'
import * as path from 'node:path'

import {nanoid} from 'nanoid'
import {rimrafSync} from 'rimraf'

// Invariably obliterate contents of the rootDirectory upon
// mtui startup if their mtime is older than this duration
// before the current date.
const ancient = 7 * 24 * 60 * 60 * 1000

const ourTemporaryDirectories = []

const rootDirectory = path.join(os.homedir(), '.mtui', 'tmp')

function obliterateTemporaryDirectory(tempdir) {
  const rel = path.relative(rootDirectory, tempdir)
  if (rel.startsWith('/') || rel.startsWith('.')) {
    console.trace()
    console.error(`Ostensible tempdir located here:`)
    console.error(tempdir)
    console.error(`Doesn't appear to be located in tempdir root:`)
    console.error(rootDirectory)
    console.error(`This is a programming error, and possibly dangerous.`)
    console.error(`So, exiting now. This should be investigated.`)
    process.exit(1)
  }

  rimrafSync(tempdir)
}

function cleanupAncient() {
  const fsOp = (fn, ...args) => {
    try {
      return fn(...args)
    } catch (error) {
      console.error(error)
      console.error(`There was an error preparing the temporary file directory.`)
      console.error(`You may be able to resolve this by deleting or moving away`)
      console.error(`this path:`)
      console.error(rootDirectory)
      process.exit(1)
    }
  }

  fsOp(() =>
    mkdirSync(rootDirectory, {recursive: true}))

  const tempdirs =
    (fsOp(readdirSync, rootDirectory)
      .map(dir => path.join(rootDirectory, dir)))

  let first = true
  for (const tempdir of tempdirs) {
    const stats = fsOp(statSync, tempdir)

    if (Date.now() - stats.mtimeMs > ancient) {
      if (first) {
        console.log(`One or more tempdirs haven't been modified in a while, removing:`)
        first = false
      }
      console.log(tempdir)
      fsOp(obliterateTemporaryDirectory, tempdir)
    }
  }
}

// This has to be a sync function, since it'll run on
// the process' 'exit' event.
function cleanupOurs() {
  for (const tempdir of ourTemporaryDirectories) {
    obliterateTemporaryDirectory(tempdir)
  }
}

cleanupAncient()
process.on('exit', cleanupOurs)

export default function temporaryDirectory() {
  const name = nanoid()
  const dir = path.join(rootDirectory, name)
  ourTemporaryDirectories.push(dir)
  mkdirSync(dir)
  return dir
}