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

59 lines
1.6 KiB

6 years ago
import { Writer } from 'clitastic'
import { config, VERBOSE } from './autorestic'
import { Backend, Backends } from './types'
import { exec, ConfigError } 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 backend.path
case 'b2':
case 'azure':
case 'gs':
case 's3':
return `${backend.type}:${backend.path}`
case 'sftp':
case 'rest':
throw new Error(`Unsupported backend type: "${backend.type}"`)
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 checkAndConfigureBackend = (name: string, backend: Backend) => {
const writer = new Writer(name.blue + ' : ' + 'Configuring... ⏳')
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)
6 years ago
}
export const checkAndConfigureBackends = (backends?: Backends) => {
if (!backends) {
if (!config) throw ConfigError
backends = config.backends
}
6 years ago
console.log('\nConfiguring Backends'.grey.underline)
for (const [name, backend] of Object.entries(backends))
checkAndConfigureBackend(name, backend)
}