mirror of
https://github.com/cupcakearmy/autorestic.git
synced 2025-01-22 14:56:24 +00:00
formatting & trailing commas
This commit is contained in:
parent
b68dc75053
commit
352754dad9
@ -5,23 +5,25 @@ import { init } from './config'
|
|||||||
import handlers, { error, help } from './handlers'
|
import handlers, { error, help } from './handlers'
|
||||||
import { Config } from './types'
|
import { Config } from './types'
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
process.on('uncaughtException', err => {
|
process.on('uncaughtException', err => {
|
||||||
console.log(err.message)
|
console.log(err.message)
|
||||||
process.exit(1)
|
process.exit(1)
|
||||||
})
|
})
|
||||||
|
|
||||||
export const { _: commands, ...flags } = minimist(process.argv.slice(2), {
|
export const { _: commands, ...flags } = minimist(process.argv.slice(2), {
|
||||||
alias: {
|
alias: {
|
||||||
c: 'config',
|
c: 'config',
|
||||||
v: 'version',
|
v: 'version',
|
||||||
h: 'help',
|
h: 'help',
|
||||||
a: 'all',
|
a: 'all',
|
||||||
l: 'location',
|
l: 'location',
|
||||||
b: 'backend',
|
b: 'backend',
|
||||||
d: 'dry-run',
|
d: 'dry-run',
|
||||||
},
|
},
|
||||||
boolean: ['a', 'd'],
|
boolean: ['a', 'd'],
|
||||||
string: ['l', 'b'],
|
string: ['l', 'b'],
|
||||||
})
|
})
|
||||||
|
|
||||||
export const VERSION = '0.6'
|
export const VERSION = '0.6'
|
||||||
@ -30,12 +32,14 @@ export const VERBOSE = flags.verbose
|
|||||||
|
|
||||||
export const config = init()
|
export const config = init()
|
||||||
|
|
||||||
function main() {
|
|
||||||
if (commands.length < 1) return help()
|
|
||||||
|
|
||||||
const command: string = commands[0]
|
function main() {
|
||||||
const args: string[] = commands.slice(1)
|
if (commands.length < 1) return help()
|
||||||
;(handlers[command] || error)(args, flags)
|
|
||||||
|
const command: string = commands[0]
|
||||||
|
const args: string[] = commands.slice(1)
|
||||||
|
;(handlers[command] || error)(args, flags)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
main()
|
main()
|
||||||
|
@ -4,55 +4,57 @@ import { config, VERBOSE } from './autorestic'
|
|||||||
import { Backend, Backends } from './types'
|
import { Backend, Backends } from './types'
|
||||||
import { exec, ConfigError } from './utils'
|
import { exec, ConfigError } from './utils'
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
const ALREADY_EXISTS = /(?=.*already)(?=.*config).*/
|
const ALREADY_EXISTS = /(?=.*already)(?=.*config).*/
|
||||||
|
|
||||||
export const getPathFromBackend = (backend: Backend): string => {
|
export const getPathFromBackend = (backend: Backend): string => {
|
||||||
switch (backend.type) {
|
switch (backend.type) {
|
||||||
case 'local':
|
case 'local':
|
||||||
return backend.path
|
return backend.path
|
||||||
case 'b2':
|
case 'b2':
|
||||||
case 'azure':
|
case 'azure':
|
||||||
case 'gs':
|
case 'gs':
|
||||||
case 's3':
|
case 's3':
|
||||||
return `${backend.type}:${backend.path}`
|
return `${backend.type}:${backend.path}`
|
||||||
case 'sftp':
|
case 'sftp':
|
||||||
case 'rest':
|
case 'rest':
|
||||||
throw new Error(`Unsupported backend type: "${backend.type}"`)
|
throw new Error(`Unsupported backend type: "${backend.type}"`)
|
||||||
default:
|
default:
|
||||||
throw new Error(`Unknown backend type.`)
|
throw new Error(`Unknown backend type.`)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export const getEnvFromBackend = (backend: Backend) => {
|
export const getEnvFromBackend = (backend: Backend) => {
|
||||||
const { type, path, key, ...rest } = backend
|
const { type, path, key, ...rest } = backend
|
||||||
return {
|
return {
|
||||||
RESTIC_PASSWORD: key,
|
RESTIC_PASSWORD: key,
|
||||||
RESTIC_REPOSITORY: getPathFromBackend(backend),
|
RESTIC_REPOSITORY: getPathFromBackend(backend),
|
||||||
...rest,
|
...rest,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export const checkAndConfigureBackend = (name: string, backend: Backend) => {
|
export const checkAndConfigureBackend = (name: string, backend: Backend) => {
|
||||||
const writer = new Writer(name.blue + ' : ' + 'Configuring... ⏳')
|
const writer = new Writer(name.blue + ' : ' + 'Configuring... ⏳')
|
||||||
const env = getEnvFromBackend(backend)
|
const env = getEnvFromBackend(backend)
|
||||||
|
|
||||||
const { out, err } = exec('restic', ['init'], { env })
|
const { out, err } = exec('restic', ['init'], { env })
|
||||||
|
|
||||||
if (err.length > 0 && !ALREADY_EXISTS.test(err))
|
if (err.length > 0 && !ALREADY_EXISTS.test(err))
|
||||||
throw new Error(`Could not load the backend "${name}": ${err}`)
|
throw new Error(`Could not load the backend "${name}": ${err}`)
|
||||||
|
|
||||||
if (VERBOSE && out.length > 0) console.log(out)
|
if (VERBOSE && out.length > 0) console.log(out)
|
||||||
|
|
||||||
writer.done(name.blue + ' : ' + 'Done ✓'.green)
|
writer.done(name.blue + ' : ' + 'Done ✓'.green)
|
||||||
}
|
}
|
||||||
|
|
||||||
export const checkAndConfigureBackends = (backends?: Backends) => {
|
export const checkAndConfigureBackends = (backends?: Backends) => {
|
||||||
if (!backends) {
|
if (!backends) {
|
||||||
if (!config) throw ConfigError
|
if (!config) throw ConfigError
|
||||||
backends = config.backends
|
backends = config.backends
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log('\nConfiguring Backends'.grey.underline)
|
console.log('\nConfiguring Backends'.grey.underline)
|
||||||
for (const [name, backend] of Object.entries(backends))
|
for (const [name, backend] of Object.entries(backends))
|
||||||
checkAndConfigureBackend(name, backend)
|
checkAndConfigureBackend(name, backend)
|
||||||
}
|
}
|
||||||
|
@ -5,42 +5,44 @@ import { getEnvFromBackend } from './backend'
|
|||||||
import { Locations, Location } from './types'
|
import { Locations, Location } from './types'
|
||||||
import { exec, ConfigError, pathRelativeToConfigFile } from './utils'
|
import { exec, ConfigError, pathRelativeToConfigFile } from './utils'
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
export const backupSingle = (name: string, from: string, to: string) => {
|
export const backupSingle = (name: string, from: string, to: string) => {
|
||||||
if (!config) throw ConfigError
|
if (!config) throw ConfigError
|
||||||
const writer = new Writer(name + to.blue + ' : ' + 'Backing up... ⏳')
|
const writer = new Writer(name + to.blue + ' : ' + 'Backing up... ⏳')
|
||||||
const backend = config.backends[to]
|
const backend = config.backends[to]
|
||||||
|
|
||||||
const path = pathRelativeToConfigFile(to)
|
const path = pathRelativeToConfigFile(to)
|
||||||
|
|
||||||
const cmd = exec('restic', ['backup', path], {
|
const cmd = exec('restic', ['backup', path], {
|
||||||
env: getEnvFromBackend(backend),
|
env: getEnvFromBackend(backend),
|
||||||
})
|
})
|
||||||
|
|
||||||
if (VERBOSE) console.log(cmd.out, cmd.err)
|
if (VERBOSE) console.log(cmd.out, cmd.err)
|
||||||
writer.done(name + to.blue + ' : ' + 'Done ✓'.green)
|
writer.done(name + to.blue + ' : ' + 'Done ✓'.green)
|
||||||
}
|
}
|
||||||
|
|
||||||
export const backupLocation = (name: string, backup: Location) => {
|
export const backupLocation = (name: string, backup: Location) => {
|
||||||
const display = name.yellow + ' ▶ '
|
const display = name.yellow + ' ▶ '
|
||||||
if (Array.isArray(backup.to)) {
|
if (Array.isArray(backup.to)) {
|
||||||
let first = true
|
let first = true
|
||||||
for (const t of backup.to) {
|
for (const t of backup.to) {
|
||||||
const nameOrBlankSpaces: string = first
|
const nameOrBlankSpaces: string = first
|
||||||
? display
|
? display
|
||||||
: new Array(name.length + 3).fill(' ').join('')
|
: new Array(name.length + 3).fill(' ').join('')
|
||||||
backupSingle(nameOrBlankSpaces, backup.from, t)
|
backupSingle(nameOrBlankSpaces, backup.from, t)
|
||||||
if (first) first = false
|
if (first) first = false
|
||||||
}
|
}
|
||||||
} else backupSingle(display, backup.from, backup.to)
|
} else backupSingle(display, backup.from, backup.to)
|
||||||
}
|
}
|
||||||
|
|
||||||
export const backupAll = (backups?: Locations) => {
|
export const backupAll = (backups?: Locations) => {
|
||||||
if (!backups) {
|
if (!backups) {
|
||||||
if (!config) throw ConfigError
|
if (!config) throw ConfigError
|
||||||
backups = config.locations
|
backups = config.locations
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log('\nBacking Up'.underline.grey)
|
console.log('\nBacking Up'.underline.grey)
|
||||||
for (const [name, backup] of Object.entries(backups))
|
for (const [name, backup] of Object.entries(backups))
|
||||||
backupLocation(name, backup)
|
backupLocation(name, backup)
|
||||||
}
|
}
|
||||||
|
113
src/config.ts
113
src/config.ts
@ -6,81 +6,84 @@ import { Backend, Config } from './types'
|
|||||||
import { makeObjectKeysLowercase, rand } from './utils'
|
import { makeObjectKeysLowercase, rand } from './utils'
|
||||||
import { homedir } from 'os'
|
import { homedir } from 'os'
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
export const normalizeAndCheckBackends = (config: Config) => {
|
export const normalizeAndCheckBackends = (config: Config) => {
|
||||||
config.backends = makeObjectKeysLowercase(config.backends)
|
config.backends = makeObjectKeysLowercase(config.backends)
|
||||||
|
|
||||||
for (const [name, { type, path, key, ...rest }] of Object.entries(
|
for (const [name, { type, path, key, ...rest }] of Object.entries(
|
||||||
config.backends
|
config.backends,
|
||||||
)) {
|
)) {
|
||||||
if (!type || !path)
|
if (!type || !path)
|
||||||
throw new Error(
|
throw new Error(
|
||||||
`The backend "${name}" is missing some required attributes`
|
`The backend "${name}" is missing some required attributes`,
|
||||||
)
|
)
|
||||||
|
|
||||||
const tmp: any = {
|
const tmp: any = {
|
||||||
type,
|
type,
|
||||||
path,
|
path,
|
||||||
key: key || rand(128),
|
key: key || rand(128),
|
||||||
}
|
}
|
||||||
for (const [key, value] of Object.entries(rest))
|
for (const [key, value] of Object.entries(rest))
|
||||||
tmp[key.toUpperCase()] = value
|
tmp[key.toUpperCase()] = value
|
||||||
|
|
||||||
config.backends[name] = tmp as Backend
|
config.backends[name] = tmp as Backend
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export const normalizeAndCheckBackups = (config: Config) => {
|
export const normalizeAndCheckBackups = (config: Config) => {
|
||||||
config.locations = makeObjectKeysLowercase(config.locations)
|
config.locations = makeObjectKeysLowercase(config.locations)
|
||||||
const backends = Object.keys(config.backends)
|
const backends = Object.keys(config.backends)
|
||||||
|
|
||||||
const checkDestination = (backend: string, backup: string) => {
|
const checkDestination = (backend: string, backup: string) => {
|
||||||
if (!backends.includes(backend))
|
if (!backends.includes(backend))
|
||||||
throw new Error(`Cannot find the backend "${backend}" for "${backup}"`)
|
throw new Error(`Cannot find the backend "${backend}" for "${backup}"`)
|
||||||
}
|
}
|
||||||
|
|
||||||
for (const [name, { from, to, ...rest }] of Object.entries(
|
for (const [name, { from, to, ...rest }] of Object.entries(
|
||||||
config.locations
|
config.locations,
|
||||||
)) {
|
)) {
|
||||||
if (!from || !to)
|
if (!from || !to)
|
||||||
throw new Error(
|
throw new Error(
|
||||||
`The backup "${name}" is missing some required attributes`
|
`The backup "${name}" is missing some required attributes`,
|
||||||
)
|
)
|
||||||
|
|
||||||
if (Array.isArray(to)) for (const t of to) checkDestination(t, name)
|
if (Array.isArray(to)) for (const t of to) checkDestination(t, name)
|
||||||
else checkDestination(to, name)
|
else checkDestination(to, name)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const findConfigFile = (): string | undefined => {
|
const findConfigFile = (): string | undefined => {
|
||||||
const config = '.autorestic.yml'
|
const config = '.autorestic.yml'
|
||||||
const paths = [
|
const paths = [
|
||||||
resolve(flags.config || ''),
|
resolve(flags.config || ''),
|
||||||
resolve('./' + config),
|
resolve('./' + config),
|
||||||
homedir() + '/' + config,
|
homedir() + '/' + config,
|
||||||
]
|
]
|
||||||
for (const path of paths) {
|
for (const path of paths) {
|
||||||
try {
|
try {
|
||||||
const file = statSync(path)
|
const file = statSync(path)
|
||||||
if (file.isFile()) return path
|
if (file.isFile()) return path
|
||||||
} catch (e) {}
|
} catch (e) {
|
||||||
}
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export let CONFIG_FILE: string = ''
|
export let CONFIG_FILE: string = ''
|
||||||
|
|
||||||
export const init = (): Config | undefined => {
|
export const init = (): Config | undefined => {
|
||||||
const file = findConfigFile()
|
const file = findConfigFile()
|
||||||
if (file) CONFIG_FILE = file
|
if (file) CONFIG_FILE = file
|
||||||
else return
|
else return
|
||||||
|
|
||||||
const raw: Config = makeObjectKeysLowercase(
|
const raw: Config = makeObjectKeysLowercase(
|
||||||
yaml.safeLoad(readFileSync(CONFIG_FILE).toString())
|
yaml.safeLoad(readFileSync(CONFIG_FILE).toString()),
|
||||||
)
|
)
|
||||||
|
|
||||||
normalizeAndCheckBackends(raw)
|
normalizeAndCheckBackends(raw)
|
||||||
normalizeAndCheckBackups(raw)
|
normalizeAndCheckBackups(raw)
|
||||||
|
|
||||||
writeFileSync(CONFIG_FILE, yaml.safeDump(raw))
|
writeFileSync(CONFIG_FILE, yaml.safeDump(raw))
|
||||||
|
|
||||||
return raw
|
return raw
|
||||||
}
|
}
|
||||||
|
@ -5,56 +5,57 @@ import { getEnvFromBackend } from './backend'
|
|||||||
import { Locations, Location, ForgetPolicy, Flags } from './types'
|
import { Locations, Location, ForgetPolicy, Flags } from './types'
|
||||||
import { exec, ConfigError } from './utils'
|
import { exec, ConfigError } from './utils'
|
||||||
|
|
||||||
export const forgetSingle = (dryRun: boolean, name: string, from: string, to: string, policy: ForgetPolicy) => {
|
|
||||||
if (!config) throw ConfigError
|
|
||||||
const writer = new Writer(name + to.blue + ' : ' + 'Removing old spnapshots… ⏳')
|
|
||||||
const backend = config.backends[to]
|
|
||||||
const flags = [] as any[]
|
|
||||||
for (const [name, value] of Object.entries(policy)) {
|
|
||||||
flags.push(`--keep-${name}`)
|
|
||||||
flags.push(value)
|
|
||||||
}
|
|
||||||
if (dryRun) {
|
|
||||||
flags.push('--dry-run')
|
|
||||||
}
|
|
||||||
const env = getEnvFromBackend(backend)
|
|
||||||
writer.replaceLn(name + to.blue + ' : ' + 'Forgeting old snapshots… ⏳')
|
|
||||||
const cmd = exec('restic', ['forget', '--path', from, '--prune', ...flags], { env })
|
|
||||||
|
|
||||||
if (VERBOSE) console.log(cmd.out, cmd.err)
|
|
||||||
writer.done(name + to.blue + ' : ' + 'Done ✓'.green)
|
export const forgetSingle = (dryRun: boolean, name: string, from: string, to: string, policy: ForgetPolicy) => {
|
||||||
|
if (!config) throw ConfigError
|
||||||
|
const writer = new Writer(name + to.blue + ' : ' + 'Removing old spnapshots… ⏳')
|
||||||
|
const backend = config.backends[to]
|
||||||
|
const flags = [] as any[]
|
||||||
|
for (const [name, value] of Object.entries(policy)) {
|
||||||
|
flags.push(`--keep-${name}`)
|
||||||
|
flags.push(value)
|
||||||
|
}
|
||||||
|
if (dryRun) {
|
||||||
|
flags.push('--dry-run')
|
||||||
|
}
|
||||||
|
const env = getEnvFromBackend(backend)
|
||||||
|
writer.replaceLn(name + to.blue + ' : ' + 'Forgeting old snapshots… ⏳')
|
||||||
|
const cmd = exec('restic', ['forget', '--path', from, '--prune', ...flags], { env })
|
||||||
|
|
||||||
|
if (VERBOSE) console.log(cmd.out, cmd.err)
|
||||||
|
writer.done(name + to.blue + ' : ' + 'Done ✓'.green)
|
||||||
}
|
}
|
||||||
|
|
||||||
export const forgetLocation = (dryRun: boolean, name: string, backup: Location, policy?: ForgetPolicy) => {
|
export const forgetLocation = (dryRun: boolean, name: string, backup: Location, policy?: ForgetPolicy) => {
|
||||||
const display = name.yellow + ' ▶ '
|
const display = name.yellow + ' ▶ '
|
||||||
if (!policy) {
|
if (!policy) {
|
||||||
console.log(display + 'skipping, no policy declared')
|
console.log(display + 'skipping, no policy declared')
|
||||||
}
|
} else {
|
||||||
else {
|
if (Array.isArray(backup.to)) {
|
||||||
if (Array.isArray(backup.to)) {
|
let first = true
|
||||||
let first = true
|
for (const t of backup.to) {
|
||||||
for (const t of backup.to) {
|
const nameOrBlankSpaces: string = first
|
||||||
const nameOrBlankSpaces: string = first
|
? display
|
||||||
? display
|
: new Array(name.length + 3).fill(' ').join('')
|
||||||
: new Array(name.length + 3).fill(' ').join('')
|
forgetSingle(dryRun, nameOrBlankSpaces, backup.from, t, policy)
|
||||||
forgetSingle(dryRun, nameOrBlankSpaces, backup.from, t, policy)
|
if (first) first = false
|
||||||
if (first) first = false
|
}
|
||||||
}
|
} else forgetSingle(dryRun, display, backup.from, backup.to, policy)
|
||||||
} else forgetSingle(dryRun, display, backup.from, backup.to, policy)
|
}
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export const forgetAll = (dryRun: boolean, backups?: Locations) => {
|
export const forgetAll = (dryRun: boolean, backups?: Locations) => {
|
||||||
if (!config) throw ConfigError
|
if (!config) throw ConfigError
|
||||||
if (!backups) {
|
if (!backups) {
|
||||||
backups = config.locations
|
backups = config.locations
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log('\nRemoving old shapshots according to policy'.underline.grey)
|
console.log('\nRemoving old shapshots according to policy'.underline.grey)
|
||||||
if (dryRun) console.log('Running in dry-run mode, not touching data\n'.yellow)
|
if (dryRun) console.log('Running in dry-run mode, not touching data\n'.yellow)
|
||||||
|
|
||||||
for (const [name, backup] of Object.entries(backups)) {
|
for (const [name, backup] of Object.entries(backups)) {
|
||||||
var policy = config.locations[name].keep
|
var policy = config.locations[name].keep
|
||||||
forgetLocation(dryRun, name, backup, policy)
|
forgetLocation(dryRun, name, backup, policy)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
417
src/handlers.ts
417
src/handlers.ts
@ -10,253 +10,256 @@ import { backupAll } from './backup'
|
|||||||
import { forgetAll } from './forget'
|
import { forgetAll } from './forget'
|
||||||
import { Backends, Flags, Locations } from './types'
|
import { Backends, Flags, Locations } from './types'
|
||||||
import {
|
import {
|
||||||
checkIfCommandIsAvailable,
|
checkIfCommandIsAvailable,
|
||||||
checkIfResticIsAvailable,
|
checkIfResticIsAvailable,
|
||||||
downloadFile,
|
downloadFile,
|
||||||
exec,
|
exec,
|
||||||
filterObjectByKey,
|
filterObjectByKey,
|
||||||
singleToArray,
|
singleToArray,
|
||||||
ConfigError,
|
ConfigError,
|
||||||
} from './utils'
|
} from './utils'
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
export type Handlers = {
|
export type Handlers = {
|
||||||
[command: string]: (args: string[], flags: Flags) => void
|
[command: string]: (args: string[], flags: Flags) => void
|
||||||
}
|
}
|
||||||
|
|
||||||
const parseBackend = (flags: Flags): Backends => {
|
const parseBackend = (flags: Flags): Backends => {
|
||||||
if (!config) throw ConfigError
|
if (!config) throw ConfigError
|
||||||
if (!flags.all && !flags.backend)
|
if (!flags.all && !flags.backend)
|
||||||
throw new Error(
|
throw new Error(
|
||||||
'No backends specified.'.red +
|
'No backends specified.'.red +
|
||||||
'\n--all [-a]\t\t\t\tCheck all.' +
|
'\n--all [-a]\t\t\t\tCheck all.' +
|
||||||
'\n--backend [-b] myBackend\t\tSpecify one or more backend'
|
'\n--backend [-b] myBackend\t\tSpecify one or more backend',
|
||||||
)
|
)
|
||||||
if (flags.all) return config.backends
|
if (flags.all) return config.backends
|
||||||
else {
|
else {
|
||||||
const backends = singleToArray<string>(flags.backend)
|
const backends = singleToArray<string>(flags.backend)
|
||||||
for (const backend of backends)
|
for (const backend of backends)
|
||||||
if (!config.backends[backend])
|
if (!config.backends[backend])
|
||||||
throw new Error('Invalid backend: '.red + backend)
|
throw new Error('Invalid backend: '.red + backend)
|
||||||
return filterObjectByKey(config.backends, backends)
|
return filterObjectByKey(config.backends, backends)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const parseLocations = (flags: Flags): Locations => {
|
const parseLocations = (flags: Flags): Locations => {
|
||||||
if (!config) throw ConfigError
|
if (!config) throw ConfigError
|
||||||
if (!flags.all && !flags.location)
|
if (!flags.all && !flags.location)
|
||||||
throw new Error(
|
throw new Error(
|
||||||
'No locations specified.'.red +
|
'No locations specified.'.red +
|
||||||
'\n--all [-a]\t\t\t\tBackup all.' +
|
'\n--all [-a]\t\t\t\tBackup all.' +
|
||||||
'\n--location [-l] site1\t\t\tSpecify one or more locations'
|
'\n--location [-l] site1\t\t\tSpecify one or more locations',
|
||||||
)
|
)
|
||||||
|
|
||||||
if (flags.all) {
|
if (flags.all) {
|
||||||
return config.locations
|
return config.locations
|
||||||
} else {
|
} else {
|
||||||
const locations = singleToArray<string>(flags.location)
|
const locations = singleToArray<string>(flags.location)
|
||||||
for (const location of locations)
|
for (const location of locations)
|
||||||
if (!config.locations[location])
|
if (!config.locations[location])
|
||||||
throw new Error('Invalid location: '.red + location)
|
throw new Error('Invalid location: '.red + location)
|
||||||
return filterObjectByKey(config.locations, locations)
|
return filterObjectByKey(config.locations, locations)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const handlers: Handlers = {
|
const handlers: Handlers = {
|
||||||
check(args, flags) {
|
check(args, flags) {
|
||||||
checkIfResticIsAvailable()
|
checkIfResticIsAvailable()
|
||||||
const backends = parseBackend(flags)
|
const backends = parseBackend(flags)
|
||||||
checkAndConfigureBackends(backends)
|
checkAndConfigureBackends(backends)
|
||||||
},
|
},
|
||||||
backup(args, flags) {
|
backup(args, flags) {
|
||||||
if (!config) throw ConfigError
|
if (!config) throw ConfigError
|
||||||
checkIfResticIsAvailable()
|
checkIfResticIsAvailable()
|
||||||
const locations: Locations = parseLocations(flags)
|
const locations: Locations = parseLocations(flags)
|
||||||
|
|
||||||
const backends = new Set<string>()
|
const backends = new Set<string>()
|
||||||
for (const to of Object.values(locations).map(location => location.to))
|
for (const to of Object.values(locations).map(location => location.to))
|
||||||
Array.isArray(to) ? to.forEach(t => backends.add(t)) : backends.add(to)
|
Array.isArray(to) ? to.forEach(t => backends.add(t)) : backends.add(to)
|
||||||
|
|
||||||
checkAndConfigureBackends(
|
checkAndConfigureBackends(
|
||||||
filterObjectByKey(config.backends, Array.from(backends))
|
filterObjectByKey(config.backends, Array.from(backends)),
|
||||||
)
|
)
|
||||||
backupAll(locations)
|
backupAll(locations)
|
||||||
|
|
||||||
console.log('\nFinished!'.underline + ' 🎉')
|
console.log('\nFinished!'.underline + ' 🎉')
|
||||||
},
|
},
|
||||||
restore(args, flags) {
|
restore(args, flags) {
|
||||||
if (!config) throw ConfigError
|
if (!config) throw ConfigError
|
||||||
checkIfResticIsAvailable()
|
checkIfResticIsAvailable()
|
||||||
const locations = parseLocations(flags)
|
const locations = parseLocations(flags)
|
||||||
for (const [name, location] of Object.entries(locations)) {
|
for (const [name, location] of Object.entries(locations)) {
|
||||||
const w = new Writer(name.green + `\t\tRestoring... ⏳`)
|
const w = new Writer(name.green + `\t\tRestoring... ⏳`)
|
||||||
const env = getEnvFromBackend(
|
const env = getEnvFromBackend(
|
||||||
config.backends[
|
config.backends[
|
||||||
Array.isArray(location.to) ? location.to[0] : location.to
|
Array.isArray(location.to) ? location.to[0] : location.to
|
||||||
]
|
],
|
||||||
)
|
)
|
||||||
|
|
||||||
exec(
|
exec(
|
||||||
'restic',
|
'restic',
|
||||||
['restore', 'latest', '--path', resolve(location.from), ...args],
|
['restore', 'latest', '--path', resolve(location.from), ...args],
|
||||||
{ env }
|
{ env },
|
||||||
)
|
)
|
||||||
w.done(name.green + '\t\tDone 🎉')
|
w.done(name.green + '\t\tDone 🎉')
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
forget(args, flags) {
|
forget(args, flags) {
|
||||||
if (!config) throw ConfigError
|
if (!config) throw ConfigError
|
||||||
checkIfResticIsAvailable()
|
checkIfResticIsAvailable()
|
||||||
const locations: Locations = parseLocations(flags)
|
const locations: Locations = parseLocations(flags)
|
||||||
|
|
||||||
const backends = new Set<string>()
|
const backends = new Set<string>()
|
||||||
for (const to of Object.values(locations).map(location => location.to))
|
for (const to of Object.values(locations).map(location => location.to))
|
||||||
Array.isArray(to) ? to.forEach(t => backends.add(t)) : backends.add(to)
|
Array.isArray(to) ? to.forEach(t => backends.add(t)) : backends.add(to)
|
||||||
|
|
||||||
checkAndConfigureBackends(
|
checkAndConfigureBackends(
|
||||||
filterObjectByKey(config.backends, Array.from(backends))
|
filterObjectByKey(config.backends, Array.from(backends)),
|
||||||
)
|
)
|
||||||
forgetAll(flags['dry-run'], locations)
|
forgetAll(flags['dry-run'], locations)
|
||||||
|
|
||||||
console.log('\nFinished!'.underline + ' 🎉')
|
console.log('\nFinished!'.underline + ' 🎉')
|
||||||
},
|
},
|
||||||
exec(args, flags) {
|
exec(args, flags) {
|
||||||
checkIfResticIsAvailable()
|
checkIfResticIsAvailable()
|
||||||
const backends = parseBackend(flags)
|
const backends = parseBackend(flags)
|
||||||
for (const [name, backend] of Object.entries(backends)) {
|
for (const [name, backend] of Object.entries(backends)) {
|
||||||
console.log(`\n${name}:\n`.grey.underline)
|
console.log(`\n${name}:\n`.grey.underline)
|
||||||
const env = getEnvFromBackend(backend)
|
const env = getEnvFromBackend(backend)
|
||||||
|
|
||||||
const { out, err } = exec('restic', args, { env })
|
const { out, err } = exec('restic', args, { env })
|
||||||
console.log(out, err)
|
console.log(out, err)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
async install() {
|
async install() {
|
||||||
try {
|
try {
|
||||||
checkIfResticIsAvailable()
|
checkIfResticIsAvailable()
|
||||||
console.log('Restic is already installed')
|
console.log('Restic is already installed')
|
||||||
return
|
return
|
||||||
} catch (e) {}
|
} catch (e) {
|
||||||
|
}
|
||||||
|
|
||||||
const w = new Writer('Checking latest version... ⏳')
|
const w = new Writer('Checking latest version... ⏳')
|
||||||
checkIfCommandIsAvailable('bzip2')
|
checkIfCommandIsAvailable('bzip2')
|
||||||
const { data: json } = await axios({
|
const { data: json } = await axios({
|
||||||
method: 'get',
|
method: 'get',
|
||||||
url: 'https://api.github.com/repos/restic/restic/releases/latest',
|
url: 'https://api.github.com/repos/restic/restic/releases/latest',
|
||||||
responseType: 'json',
|
responseType: 'json',
|
||||||
})
|
})
|
||||||
|
|
||||||
const archMap: { [a: string]: string } = {
|
const archMap: { [a: string]: string } = {
|
||||||
x32: '386',
|
x32: '386',
|
||||||
x64: 'amd64',
|
x64: 'amd64',
|
||||||
}
|
}
|
||||||
|
|
||||||
w.replaceLn('Downloading binary... 🌎')
|
w.replaceLn('Downloading binary... 🌎')
|
||||||
const name = `${json.name.replace(' ', '_')}_${process.platform}_${
|
const name = `${json.name.replace(' ', '_')}_${process.platform}_${
|
||||||
archMap[process.arch]
|
archMap[process.arch]
|
||||||
}.bz2`
|
}.bz2`
|
||||||
const dl = json.assets.find((asset: any) => asset.name === name)
|
const dl = json.assets.find((asset: any) => asset.name === name)
|
||||||
if (!dl)
|
if (!dl)
|
||||||
return console.log(
|
return console.log(
|
||||||
'Cannot get the right binary.'.red,
|
'Cannot get the right binary.'.red,
|
||||||
'Please see https://bit.ly/2Y1Rzai'
|
'Please see https://bit.ly/2Y1Rzai',
|
||||||
)
|
)
|
||||||
|
|
||||||
const tmp = join(tmpdir(), name)
|
const tmp = join(tmpdir(), name)
|
||||||
const extracted = tmp.slice(0, -4) //without the .bz2
|
const extracted = tmp.slice(0, -4) //without the .bz2
|
||||||
|
|
||||||
await downloadFile(dl.browser_download_url, tmp)
|
await downloadFile(dl.browser_download_url, tmp)
|
||||||
|
|
||||||
// TODO: Native bz2
|
// TODO: Native bz2
|
||||||
// Decompress
|
// Decompress
|
||||||
w.replaceLn('Decompressing binary... 📦')
|
w.replaceLn('Decompressing binary... 📦')
|
||||||
exec('bzip2', ['-dk', tmp])
|
exec('bzip2', ['-dk', tmp])
|
||||||
unlinkSync(tmp)
|
unlinkSync(tmp)
|
||||||
|
|
||||||
w.replaceLn(`Moving to ${INSTALL_DIR} 🚙`)
|
w.replaceLn(`Moving to ${INSTALL_DIR} 🚙`)
|
||||||
exec('chmod', ['+x', extracted])
|
exec('chmod', ['+x', extracted])
|
||||||
exec('mv', [extracted, INSTALL_DIR + '/restic'])
|
exec('mv', [extracted, INSTALL_DIR + '/restic'])
|
||||||
|
|
||||||
w.done(
|
w.done(
|
||||||
`\nFinished! restic is installed under: ${INSTALL_DIR}`.underline + ' 🎉'
|
`\nFinished! restic is installed under: ${INSTALL_DIR}`.underline + ' 🎉',
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
uninstall() {
|
uninstall() {
|
||||||
for (const bin of ['restic', 'autorestic'])
|
for (const bin of ['restic', 'autorestic'])
|
||||||
try {
|
try {
|
||||||
unlinkSync(INSTALL_DIR + '/' + bin)
|
unlinkSync(INSTALL_DIR + '/' + bin)
|
||||||
console.log(`Finished! ${bin} was uninstalled`)
|
console.log(`Finished! ${bin} was uninstalled`)
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.log(`${bin} is already uninstalled`.red)
|
console.log(`${bin} is already uninstalled`.red)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
async update() {
|
async update() {
|
||||||
checkIfResticIsAvailable()
|
checkIfResticIsAvailable()
|
||||||
const w = new Writer('Checking for latest restic version... ⏳')
|
const w = new Writer('Checking for latest restic version... ⏳')
|
||||||
exec('restic', ['self-update'])
|
exec('restic', ['self-update'])
|
||||||
|
|
||||||
w.replaceLn('Checking for latest autorestic version... ⏳')
|
w.replaceLn('Checking for latest autorestic version... ⏳')
|
||||||
const { data: json } = await axios({
|
const { data: json } = await axios({
|
||||||
method: 'get',
|
method: 'get',
|
||||||
url:
|
url:
|
||||||
'https://api.github.com/repos/cupcakearmy/autorestic/releases/latest',
|
'https://api.github.com/repos/cupcakearmy/autorestic/releases/latest',
|
||||||
responseType: 'json',
|
responseType: 'json',
|
||||||
})
|
})
|
||||||
|
|
||||||
if (json.tag_name != VERSION) {
|
if (json.tag_name != VERSION) {
|
||||||
const platformMap: { [key: string]: string } = {
|
const platformMap: { [key: string]: string } = {
|
||||||
darwin: 'macos',
|
darwin: 'macos',
|
||||||
}
|
}
|
||||||
|
|
||||||
const name = `autorestic_${platformMap[process.platform] ||
|
const name = `autorestic_${platformMap[process.platform] ||
|
||||||
process.platform}_${process.arch}`
|
process.platform}_${process.arch}`
|
||||||
const dl = json.assets.find((asset: any) => asset.name === name)
|
const dl = json.assets.find((asset: any) => asset.name === name)
|
||||||
|
|
||||||
const to = INSTALL_DIR + '/autorestic'
|
const to = INSTALL_DIR + '/autorestic'
|
||||||
w.replaceLn('Downloading binary... 🌎')
|
w.replaceLn('Downloading binary... 🌎')
|
||||||
await downloadFile(dl.browser_download_url, to)
|
await downloadFile(dl.browser_download_url, to)
|
||||||
|
|
||||||
exec('chmod', ['+x', to])
|
exec('chmod', ['+x', to])
|
||||||
}
|
}
|
||||||
|
|
||||||
w.done('All up to date! 🚀')
|
w.done('All up to date! 🚀')
|
||||||
},
|
},
|
||||||
version() {
|
version() {
|
||||||
console.log('version'.grey, VERSION)
|
console.log('version'.grey, VERSION)
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
export const help = () => {
|
export const help = () => {
|
||||||
console.log(
|
console.log(
|
||||||
'\nAutorestic'.blue +
|
'\nAutorestic'.blue +
|
||||||
` - ${VERSION} - Easy Restic CLI Utility` +
|
` - ${VERSION} - Easy Restic CLI Utility` +
|
||||||
'\n' +
|
'\n' +
|
||||||
'\nOptions:'.yellow +
|
'\nOptions:'.yellow +
|
||||||
`\n -c, --config Specify config file. Default: .autorestic.yml` +
|
`\n -c, --config Specify config file. Default: .autorestic.yml` +
|
||||||
'\n' +
|
'\n' +
|
||||||
'\nCommands:'.yellow +
|
'\nCommands:'.yellow +
|
||||||
'\n check [-b, --backend] [-a, --all] Check backends' +
|
'\n check [-b, --backend] [-a, --all] Check backends' +
|
||||||
'\n backup [-l, --location] [-a, --all] Backup all or specified locations' +
|
'\n backup [-l, --location] [-a, --all] Backup all or specified locations' +
|
||||||
'\n forget [-l, --location] [-a, --all] [--dry-run] Forget old snapshots according to declared policies' +
|
'\n forget [-l, --location] [-a, --all] [--dry-run] Forget old snapshots according to declared policies' +
|
||||||
'\n restore [-l, --location] [-- --target <out dir>] Restore all or specified locations' +
|
'\n restore [-l, --location] [-- --target <out dir>] Restore all or specified locations' +
|
||||||
'\n' +
|
'\n' +
|
||||||
'\n exec [-b, --backend] [-a, --all] <command> -- [native options] Execute native restic command' +
|
'\n exec [-b, --backend] [-a, --all] <command> -- [native options] Execute native restic command' +
|
||||||
'\n' +
|
'\n' +
|
||||||
'\n install install restic' +
|
'\n install install restic' +
|
||||||
'\n uninstall uninstall restic' +
|
'\n uninstall uninstall restic' +
|
||||||
'\n update update restic' +
|
'\n update update restic' +
|
||||||
'\n help Show help' +
|
'\n help Show help' +
|
||||||
'\n' +
|
'\n' +
|
||||||
'\nExamples: '.yellow +
|
'\nExamples: '.yellow +
|
||||||
'https://git.io/fjVbg' +
|
'https://git.io/fjVbg' +
|
||||||
'\n'
|
'\n',
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
export const error = () => {
|
export const error = () => {
|
||||||
help()
|
help()
|
||||||
console.log(
|
console.log(
|
||||||
`Invalid Command:`.red.underline,
|
`Invalid Command:`.red.underline,
|
||||||
`${process.argv.slice(2).join(' ')}`
|
`${process.argv.slice(2).join(' ')}`,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
export default handlers
|
export default handlers
|
||||||
|
104
src/types.ts
104
src/types.ts
@ -1,89 +1,89 @@
|
|||||||
type BackendLocal = {
|
type BackendLocal = {
|
||||||
type: 'local'
|
type: 'local'
|
||||||
key: string
|
key: string
|
||||||
path: string
|
path: string
|
||||||
}
|
}
|
||||||
|
|
||||||
type BackendSFTP = {
|
type BackendSFTP = {
|
||||||
type: 'sftp'
|
type: 'sftp'
|
||||||
key: string
|
key: string
|
||||||
path: string
|
path: string
|
||||||
password?: string
|
password?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
type BackendREST = {
|
type BackendREST = {
|
||||||
type: 'rest'
|
type: 'rest'
|
||||||
key: string
|
key: string
|
||||||
path: string
|
path: string
|
||||||
user?: string
|
user?: string
|
||||||
password?: string
|
password?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
type BackendS3 = {
|
type BackendS3 = {
|
||||||
type: 's3'
|
type: 's3'
|
||||||
key: string
|
key: string
|
||||||
path: string
|
path: string
|
||||||
aws_access_key_id: string
|
aws_access_key_id: string
|
||||||
aws_secret_access_key: string
|
aws_secret_access_key: string
|
||||||
}
|
}
|
||||||
|
|
||||||
type BackendB2 = {
|
type BackendB2 = {
|
||||||
type: 'b2'
|
type: 'b2'
|
||||||
key: string
|
key: string
|
||||||
path: string
|
path: string
|
||||||
b2_account_id: string
|
b2_account_id: string
|
||||||
b2_account_key: string
|
b2_account_key: string
|
||||||
}
|
}
|
||||||
|
|
||||||
type BackendAzure = {
|
type BackendAzure = {
|
||||||
type: 'azure'
|
type: 'azure'
|
||||||
key: string
|
key: string
|
||||||
path: string
|
path: string
|
||||||
azure_account_name: string
|
azure_account_name: string
|
||||||
azure_account_key: string
|
azure_account_key: string
|
||||||
}
|
}
|
||||||
|
|
||||||
type BackendGS = {
|
type BackendGS = {
|
||||||
type: 'gs'
|
type: 'gs'
|
||||||
key: string
|
key: string
|
||||||
path: string
|
path: string
|
||||||
google_project_id: string
|
google_project_id: string
|
||||||
google_application_credentials: string
|
google_application_credentials: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export type Backend =
|
export type Backend =
|
||||||
| BackendAzure
|
| BackendAzure
|
||||||
| BackendB2
|
| BackendB2
|
||||||
| BackendGS
|
| BackendGS
|
||||||
| BackendLocal
|
| BackendLocal
|
||||||
| BackendREST
|
| BackendREST
|
||||||
| BackendS3
|
| BackendS3
|
||||||
| BackendSFTP
|
| BackendSFTP
|
||||||
|
|
||||||
export type Backends = { [name: string]: Backend }
|
export type Backends = { [name: string]: Backend }
|
||||||
|
|
||||||
export type ForgetPolicy = {
|
export type ForgetPolicy = {
|
||||||
last?: number,
|
last?: number,
|
||||||
hourly?: number,
|
hourly?: number,
|
||||||
daily?: number,
|
daily?: number,
|
||||||
weekly?: number,
|
weekly?: number,
|
||||||
monthly?: number,
|
monthly?: number,
|
||||||
yearly?: number,
|
yearly?: number,
|
||||||
within?: string,
|
within?: string,
|
||||||
tags?: string[],
|
tags?: string[],
|
||||||
}
|
}
|
||||||
|
|
||||||
export type Location = {
|
export type Location = {
|
||||||
from: string
|
from: string
|
||||||
to: string | string[]
|
to: string | string[]
|
||||||
keep?: ForgetPolicy
|
keep?: ForgetPolicy
|
||||||
}
|
}
|
||||||
|
|
||||||
export type Locations = { [name: string]: Location }
|
export type Locations = { [name: string]: Location }
|
||||||
|
|
||||||
export type Config = {
|
export type Config = {
|
||||||
locations: Locations
|
locations: Locations
|
||||||
backends: Backends
|
backends: Backends
|
||||||
}
|
}
|
||||||
|
|
||||||
export type Flags = { [arg: string]: any }
|
export type Flags = { [arg: string]: any }
|
||||||
|
94
src/utils.ts
94
src/utils.ts
@ -5,80 +5,84 @@ import { createWriteStream } from 'fs'
|
|||||||
import { isAbsolute, resolve, dirname } from 'path'
|
import { isAbsolute, resolve, dirname } from 'path'
|
||||||
import { CONFIG_FILE } from './config'
|
import { CONFIG_FILE } from './config'
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
export const exec = (
|
export const exec = (
|
||||||
command: string,
|
command: string,
|
||||||
args: string[],
|
args: string[],
|
||||||
{ env, ...rest }: SpawnSyncOptions = {}
|
{ env, ...rest }: SpawnSyncOptions = {},
|
||||||
) => {
|
) => {
|
||||||
const cmd = spawnSync(command, args, {
|
const cmd = spawnSync(command, args, {
|
||||||
...rest,
|
...rest,
|
||||||
env: {
|
env: {
|
||||||
...process.env,
|
...process.env,
|
||||||
...env,
|
...env,
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
const out = cmd.stdout && cmd.stdout.toString().trim()
|
const out = cmd.stdout && cmd.stdout.toString().trim()
|
||||||
const err = cmd.stderr && cmd.stderr.toString().trim()
|
const err = cmd.stderr && cmd.stderr.toString().trim()
|
||||||
|
|
||||||
return { out, err }
|
return { out, err }
|
||||||
}
|
}
|
||||||
|
|
||||||
export const checkIfResticIsAvailable = () =>
|
export const checkIfResticIsAvailable = () =>
|
||||||
checkIfCommandIsAvailable(
|
checkIfCommandIsAvailable(
|
||||||
'restic',
|
'restic',
|
||||||
'Restic is not installed'.red +
|
'Restic is not installed'.red +
|
||||||
' https://restic.readthedocs.io/en/latest/020_installation.html#stable-releases'
|
' https://restic.readthedocs.io/en/latest/020_installation.html#stable-releases',
|
||||||
)
|
)
|
||||||
|
|
||||||
export const checkIfCommandIsAvailable = (cmd: string, errorMsg?: string) => {
|
export const checkIfCommandIsAvailable = (cmd: string, errorMsg?: string) => {
|
||||||
if (require('child_process').spawnSync(cmd).error)
|
if (require('child_process').spawnSync(cmd).error)
|
||||||
throw new Error(errorMsg ? errorMsg : `"${errorMsg}" is not installed`.red)
|
throw new Error(errorMsg ? errorMsg : `"${errorMsg}" is not installed`.red)
|
||||||
}
|
}
|
||||||
|
|
||||||
export const makeObjectKeysLowercase = (object: Object): any =>
|
export const makeObjectKeysLowercase = (object: Object): any =>
|
||||||
Object.fromEntries(
|
Object.fromEntries(
|
||||||
Object.entries(object).map(([key, value]) => [key.toLowerCase(), value])
|
Object.entries(object).map(([key, value]) => [key.toLowerCase(), value]),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
export function rand(length = 32): string {
|
export function rand(length = 32): string {
|
||||||
return randomBytes(length / 2).toString('hex')
|
return randomBytes(length / 2).toString('hex')
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
export const singleToArray = <T>(singleOrArray: T | T[]): T[] =>
|
export const singleToArray = <T>(singleOrArray: T | T[]): T[] =>
|
||||||
Array.isArray(singleOrArray) ? singleOrArray : [singleOrArray]
|
Array.isArray(singleOrArray) ? singleOrArray : [singleOrArray]
|
||||||
|
|
||||||
export const filterObject = <T>(
|
export const filterObject = <T>(
|
||||||
obj: { [key: string]: T },
|
obj: { [key: string]: T },
|
||||||
filter: (item: [string, T]) => boolean
|
filter: (item: [string, T]) => boolean,
|
||||||
): { [key: string]: T } =>
|
): { [key: string]: T } =>
|
||||||
Object.fromEntries(Object.entries(obj).filter(filter))
|
Object.fromEntries(Object.entries(obj).filter(filter))
|
||||||
|
|
||||||
export const filterObjectByKey = <T>(
|
export const filterObjectByKey = <T>(
|
||||||
obj: { [key: string]: T },
|
obj: { [key: string]: T },
|
||||||
keys: string[]
|
keys: string[],
|
||||||
) => filterObject(obj, ([key]) => keys.includes(key))
|
) => filterObject(obj, ([key]) => keys.includes(key))
|
||||||
|
|
||||||
export const downloadFile = async (url: string, to: string) =>
|
export const downloadFile = async (url: string, to: string) =>
|
||||||
new Promise<void>(async res => {
|
new Promise<void>(async res => {
|
||||||
const { data: file } = await axios({
|
const { data: file } = await axios({
|
||||||
method: 'get',
|
method: 'get',
|
||||||
url: url,
|
url: url,
|
||||||
responseType: 'stream',
|
responseType: 'stream',
|
||||||
})
|
})
|
||||||
|
|
||||||
const stream = createWriteStream(to)
|
const stream = createWriteStream(to)
|
||||||
|
|
||||||
const writer = file.pipe(stream)
|
const writer = file.pipe(stream)
|
||||||
writer.on('close', () => {
|
writer.on('close', () => {
|
||||||
stream.close()
|
stream.close()
|
||||||
res()
|
res()
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
// Check if is an absolute path, otherwise get the path relative to the config file
|
// Check if is an absolute path, otherwise get the path relative to the config file
|
||||||
export const pathRelativeToConfigFile = (path: string): string => isAbsolute(path)
|
export const pathRelativeToConfigFile = (path: string): string => isAbsolute(path)
|
||||||
? path
|
? path
|
||||||
: resolve(dirname(CONFIG_FILE), path)
|
: resolve(dirname(CONFIG_FILE), path)
|
||||||
|
|
||||||
export const ConfigError = new Error('Config file not found')
|
export const ConfigError = new Error('Config file not found')
|
||||||
|
Loading…
Reference in New Issue
Block a user