Created
June 13, 2021 03:54
-
-
Save allancalix/58caecfcbd85368ba86eb6aaf97864c0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env node | |
// A simple script that checks for the existence of a "datelock" file. If one | |
// exists, either returns 1 (error) or 0 (success). I use this to periodically | |
// update files when a shell starts. | |
// | |
// Example usage: | |
// // Creates or overwrites a "datelock" file at LOCK_PATH. | |
// LOCK_PATH=$HOME/.datelock ./datelock.js write | |
// // Checks for a valid lock file at LOCK_PATH, returns 0 or 1. | |
// LOCK_PATH=$HOME/.datelock ./datelock.js | |
// | |
// Checking a lockfile will return 1 (error) in the following situations: | |
// 1. The datetime in the lockfile is less than the current datetime. | |
// 2. The "datelock" file does not exist. | |
// 3. A system error occurs when reading the LOCK_PATH file (e.g. permission error) | |
const fs = require("fs"); | |
const now = new Date(); | |
const lockPath = process.env.LOCK_PATH; | |
if (lockPath === "" || lockPath === undefined) { | |
console.log("Usage: LOCK_PATH=<PATH> datelock.js"); | |
process.exit(1); | |
} | |
(async () => { | |
try { | |
if (process.argv.length > 2 && process.argv[2] == "clear") { | |
const file = await fs.promises.rm(lockPath); | |
return; | |
} | |
if (process.argv.length > 2 && process.argv[2] == "write") { | |
const file = await fs.promises.open(lockPath, 'w+'); | |
let tomorrow = now; | |
tomorrow.setDate(now.getDate() + 1); | |
await file.write(tomorrow.toISOString()); | |
return; | |
} | |
const data = await fs.promises.readFile(lockPath, 'utf8'); | |
const lockDate = Date.parse(data); | |
if (isNaN(lockDate) || lockDate < now) { | |
process.exit(1); | |
} | |
} catch (_) { | |
process.exit(1); | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment