autorestic/src/backend.ts

68 lines
1.9 KiB
TypeScript
Raw Normal View History

2019-06-20 23:09:47 +02:00
import { Writer } from 'clitastic'
import { config, VERBOSE } from './autorestic'
import { Backend, Backends, Locations } from './types'
2019-12-24 16:52:27 +01:00
import { exec, ConfigError, pathRelativeToConfigFile } from './utils'
2019-06-20 23:09:47 +02:00
2019-12-03 23:37:55 +01:00
const ALREADY_EXISTS = /(?=.*already)(?=.*config).*/
2019-06-20 23:09:47 +02:00
export const getPathFromBackend = (backend: Backend): string => {
2019-12-03 23:37:55 +01:00
switch (backend.type) {
case 'local':
2019-12-24 16:52:27 +01:00
return pathRelativeToConfigFile(backend.path)
2019-12-03 23:37:55 +01:00
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.`)
}
2019-06-20 23:09:47 +02:00
}
export const getEnvFromBackend = (backend: Backend) => {
2019-12-03 23:37:55 +01:00
const { type, path, key, ...rest } = backend
return {
RESTIC_PASSWORD: key,
RESTIC_REPOSITORY: getPathFromBackend(backend),
...rest,
}
2019-06-20 23:09:47 +02:00
}
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)
}
2019-06-20 23:09:47 +02:00
export const checkAndConfigureBackend = (name: string, backend: Backend) => {
2019-12-03 23:37:55 +01:00
const writer = new Writer(name.blue + ' : ' + 'Configuring... ⏳')
const env = getEnvFromBackend(backend)
2019-06-20 23:09:47 +02:00
2019-12-03 23:37:55 +01:00
const { out, err } = exec('restic', ['init'], { env })
2019-06-20 23:09:47 +02:00
2019-12-03 23:37:55 +01:00
if (err.length > 0 && !ALREADY_EXISTS.test(err))
throw new Error(`Could not load the backend "${name}": ${err}`)
2019-06-20 23:09:47 +02:00
2019-12-03 23:37:55 +01:00
if (VERBOSE && out.length > 0) console.log(out)
2019-06-20 23:09:47 +02:00
2019-12-03 23:37:55 +01:00
writer.done(name.blue + ' : ' + 'Done ✓'.green)
2019-06-20 23:09:47 +02:00
}
export const checkAndConfigureBackends = (backends?: Backends) => {
2019-12-03 23:37:55 +01:00
if (!backends) {
if (!config) throw ConfigError
backends = config.backends
}
console.log('\nConfiguring Backends'.grey.underline)
for (const [name, backend] of Object.entries(backends))
checkAndConfigureBackend(name, backend)
}