autorestic/src/backup.ts

60 lines
1.8 KiB
TypeScript
Raw Normal View History

2019-06-20 23:09:47 +02:00
import { Writer } from 'clitastic'
import { config, VERBOSE } from './autorestic'
import { getEnvFromBackend } from './backend'
import { Locations, Location } from './types'
2019-12-05 00:24:20 +01:00
import { exec, ConfigError, pathRelativeToConfigFile, getFlagsFromLocation, makeArrayIfIsNot, execPlain } from './utils'
2019-06-20 23:09:47 +02:00
2019-12-03 23:37:55 +01:00
2019-12-04 20:38:04 +01:00
export const backupSingle = (name: string, to: string, location: Location) => {
2019-12-03 23:37:55 +01:00
if (!config) throw ConfigError
const writer = new Writer(name + to.blue + ' : ' + 'Backing up... ⏳')
2019-10-26 21:50:48 +02:00
2019-12-04 23:35:41 +01:00
const backend = config.backends[to]
2019-12-04 20:38:04 +01:00
const path = pathRelativeToConfigFile(location.from)
2019-06-20 23:09:47 +02:00
2019-12-04 20:38:04 +01:00
const cmd = exec(
'restic',
['backup', path, ...getFlagsFromLocation(location, 'backup')],
{ env: getEnvFromBackend(backend) },
)
2019-06-20 23:09:47 +02:00
2019-12-03 23:37:55 +01:00
if (VERBOSE) console.log(cmd.out, cmd.err)
writer.done(name + to.blue + ' : ' + 'Done ✓'.green)
}
2019-06-20 23:09:47 +02:00
2019-12-04 20:38:04 +01:00
export const backupLocation = (name: string, location: Location) => {
2019-12-03 23:37:55 +01:00
const display = name.yellow + ' ▶ '
2019-12-04 20:38:04 +01:00
const filler = new Array(name.length + 3).fill(' ').join('')
2019-12-04 23:35:41 +01:00
let first = true
2019-12-05 00:24:20 +01:00
if (location.hooks && location.hooks.before)
for (const command of makeArrayIfIsNot(location.hooks.before)) {
const cmd = execPlain(command)
if (cmd) console.log(cmd.out, cmd.err)
}
for (const t of makeArrayIfIsNot(location.to)) {
2019-12-04 23:35:41 +01:00
backupSingle(first ? display : filler, t, location)
if (first) first = false
}
2019-12-05 00:24:20 +01:00
if (location.hooks && location.hooks.after)
for (const command of makeArrayIfIsNot(location.hooks.after)) {
const cmd = execPlain(command)
if (cmd) console.log(cmd.out, cmd.err)
}
2019-06-20 23:09:47 +02:00
}
2019-12-04 20:38:04 +01:00
export const backupAll = (locations?: Locations) => {
if (!locations) {
2019-12-03 23:37:55 +01:00
if (!config) throw ConfigError
2019-12-04 20:38:04 +01:00
locations = config.locations
2019-12-03 23:37:55 +01:00
}
console.log('\nBacking Up'.underline.grey)
2019-12-04 20:38:04 +01:00
for (const [name, location] of Object.entries(locations))
backupLocation(name, location)
}