You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
autorestic/src/backend.ts

67 lines
2.1 KiB

6 years ago
import { Writer } from 'clitastic'
import { config, VERBOSE } from './'
import { Backend, Backends, Locations } from './types'
5 years ago
import { exec, pathRelativeToConfigFile, filterObjectByKey } from './utils'
6 years ago
const ALREADY_EXISTS = /(?=.*already)(?=.*config).*/
6 years ago
export const getPathFromBackend = (backend: Backend): string => {
switch (backend.type) {
case 'local':
return pathRelativeToConfigFile(backend.path)
case 'b2':
case 'azure':
case 'gs':
case 's3':
case 'sftp':
case 'rest':
return `${backend.type}:${backend.path}`
default:
throw new Error(`Unknown backend type.`)
}
6 years ago
}
export const getEnvFromBackend = (backend: Backend) => {
const { type, path, key, ...rest } = backend
return {
RESTIC_PASSWORD: key,
RESTIC_REPOSITORY: getPathFromBackend(backend),
...rest,
}
6 years ago
}
export const getBackendsFromLocations = (locations: Locations): string[] => {
const backends = new Set<string>()
for (const to of Object.values(locations).map((location) => location.to)) Array.isArray(to) ? to.forEach((t) => backends.add(t)) : backends.add(to)
return Array.from(backends)
}
6 years ago
export const checkAndConfigureBackend = (name: string, backend: Backend) => {
const writer = new Writer(name.blue + ' : ' + 'Configuring... ⏳')
try {
const env = getEnvFromBackend(backend)
6 years ago
const { out, err } = exec('restic', ['init'], { env })
6 years ago
if (err.length > 0 && !ALREADY_EXISTS.test(err)) throw new Error(`Could not load the backend "${name}": ${err}`)
6 years ago
if (VERBOSE && out.length > 0) console.log(out)
6 years ago
writer.done(name.blue + ' : ' + 'Done ✓'.green)
} catch (e) {
writer.done(name.blue + ' : ' + 'Error ⚠️ ' + e.message.red)
}
6 years ago
}
export const checkAndConfigureBackends = (backends?: Backends) => {
if (!backends) backends = config.backends
console.log('\nConfiguring Backends'.grey.underline)
for (const [name, backend] of Object.entries(backends)) checkAndConfigureBackend(name, backend)
}
5 years ago
export const checkAndConfigureBackendsForLocations = (locations: Locations) => {
checkAndConfigureBackends(filterObjectByKey(config.backends, getBackendsFromLocations(locations)))
5 years ago
}