pull/3/head
cupcakearmy 5 years ago
parent 3c0ebdfb4a
commit 3d1e28e574

@ -4,213 +4,233 @@ import { unlinkSync } from 'fs'
import { tmpdir } from 'os' import { tmpdir } from 'os'
import { join, resolve } from 'path' import { join, resolve } from 'path'
import { config, CONFIG_FILE, INSTALL_DIR, VERSION } from './autorestic' import { config, INSTALL_DIR, VERSION } from './autorestic'
import { checkAndConfigureBackends, getEnvFromBackend } from './backend' import { checkAndConfigureBackends, getEnvFromBackend } from './backend'
import { backupAll } from './backup' import { backupAll } from './backup'
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,
} from './utils' } from './utils'
export type Handlers = { [command: string]: (args: string[], flags: Flags) => void } export type Handlers = {
[command: string]: (args: string[], flags: Flags) => void
}
const parseBackend = (flags: Flags): Backends => { const parseBackend = (flags: Flags): Backends => {
if (!flags.all && !flags.backend) if (!flags.all && !flags.backend)
throw new Error('No backends specified.'.red throw new Error(
+ '\n--all [-a]\t\t\t\tCheck all.' 'No backends specified.'.red +
+ '\n--backend [-b] myBackend\t\tSpecify one or more backend', '\n--all [-a]\t\t\t\tCheck all.' +
) '\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 (!flags.all && !flags.location) if (!flags.all && !flags.location)
throw new Error('No locations specified.'.red throw new Error(
+ '\n--all [-a]\t\t\t\tBackup all.' 'No locations specified.'.red +
+ '\n--location [-l] site1\t\t\tSpecify one or more locations', '\n--all [-a]\t\t\t\tBackup all.' +
) '\n--location [-l] site1\t\t\tSpecify one or more locations'
)
if (flags.all) {
return config.locations if (flags.all) {
} else { return config.locations
const locations = singleToArray<string>(flags.location) } else {
for (const location of locations) const locations = singleToArray<string>(flags.location)
if (!config.locations[location]) for (const location of locations)
throw new Error('Invalid location: '.red + location) if (!config.locations[location])
return filterObjectByKey(config.locations, locations) throw new Error('Invalid location: '.red + location)
} 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) {
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(filterObjectByKey(config.backends, Array.from(backends))) checkAndConfigureBackends(
backupAll(locations) filterObjectByKey(config.backends, Array.from(backends))
)
console.log('\nFinished!'.underline + ' 🎉') backupAll(locations)
},
restore(args, flags) { console.log('\nFinished!'.underline + ' 🎉')
checkIfResticIsAvailable() },
const locations = parseLocations(flags) restore(args, flags) {
for (const [name, location] of Object.entries(locations)) { checkIfResticIsAvailable()
const w = new Writer(name.green + `\t\tRestoring... ⏳`) const locations = parseLocations(flags)
const env = getEnvFromBackend(config.backends[Array.isArray(location.to) ? location.to[0] : location.to]) for (const [name, location] of Object.entries(locations)) {
const w = new Writer(name.green + `\t\tRestoring... ⏳`)
exec( const env = getEnvFromBackend(
'restic', config.backends[
['restore', 'latest', '--path', resolve(location.from), ...args], Array.isArray(location.to) ? location.to[0] : location.to
{ env }, ]
) )
w.done(name.green + '\t\tDone 🎉')
} exec(
}, 'restic',
exec(args, flags) { ['restore', 'latest', '--path', resolve(location.from), ...args],
checkIfResticIsAvailable() { env }
const backends = parseBackend(flags) )
for (const [name, backend] of Object.entries(backends)) { w.done(name.green + '\t\tDone 🎉')
console.log(`\n${name}:\n`.grey.underline) }
const env = getEnvFromBackend(backend) },
exec(args, flags) {
const { out, err } = exec('restic', args, { env }) checkIfResticIsAvailable()
console.log(out, err) const backends = parseBackend(flags)
} for (const [name, backend] of Object.entries(backends)) {
}, console.log(`\n${name}:\n`.grey.underline)
async install() { const env = getEnvFromBackend(backend)
try {
checkIfResticIsAvailable() const { out, err } = exec('restic', args, { env })
console.log('Restic is already installed') console.log(out, err)
return }
} catch (e) { },
} async install() {
try {
const w = new Writer('Checking latest version... ⏳') checkIfResticIsAvailable()
checkIfCommandIsAvailable('bzip2') console.log('Restic is already installed')
const { data: json } = await axios({ return
method: 'get', } catch (e) {}
url: 'https://api.github.com/repos/restic/restic/releases/latest',
responseType: 'json', const w = new Writer('Checking latest version... ⏳')
}) checkIfCommandIsAvailable('bzip2')
const { data: json } = await axios({
const archMap: { [a: string]: string } = { method: 'get',
'x32': '386', url: 'https://api.github.com/repos/restic/restic/releases/latest',
'x64': 'amd64', responseType: 'json',
} })
w.replaceLn('Downloading binary... 🌎') const archMap: { [a: string]: string } = {
const name = `${json.name.replace(' ', '_')}_${process.platform}_${archMap[process.arch]}.bz2` x32: '386',
const dl = json.assets.find((asset: any) => asset.name === name) x64: 'amd64',
if (!dl) return console.log( }
'Cannot get the right binary.'.red,
'Please see https://bit.ly/2Y1Rzai', w.replaceLn('Downloading binary... 🌎')
) const name = `${json.name.replace(' ', '_')}_${process.platform}_${
archMap[process.arch]
const tmp = join(tmpdir(), name) }.bz2`
const extracted = tmp.slice(0, -4) //without the .bz2 const dl = json.assets.find((asset: any) => asset.name === name)
if (!dl)
await downloadFile(dl.browser_download_url, tmp) return console.log(
'Cannot get the right binary.'.red,
// TODO: Native bz2 'Please see https://bit.ly/2Y1Rzai'
// Decompress )
w.replaceLn('Decompressing binary... 📦')
exec('bzip2', ['-dk', tmp]) const tmp = join(tmpdir(), name)
unlinkSync(tmp) const extracted = tmp.slice(0, -4) //without the .bz2
w.replaceLn(`Moving to ${INSTALL_DIR} 🚙`) await downloadFile(dl.browser_download_url, tmp)
exec('chmod', ['+x', extracted])
exec('mv', [extracted, INSTALL_DIR + '/restic']) // TODO: Native bz2
// Decompress
w.done(`\nFinished! restic is installed under: ${INSTALL_DIR}`.underline + ' 🎉') w.replaceLn('Decompressing binary... 📦')
}, exec('bzip2', ['-dk', tmp])
uninstall() { unlinkSync(tmp)
for (const bin of ['restic', 'autorestic'])
try { w.replaceLn(`Moving to ${INSTALL_DIR} 🚙`)
unlinkSync(INSTALL_DIR + '/' + bin) exec('chmod', ['+x', extracted])
console.log(`Finished! ${bin} was uninstalled`) exec('mv', [extracted, INSTALL_DIR + '/restic'])
} catch (e) {
console.log(`${bin} is already uninstalled`.red) w.done(
} `\nFinished! restic is installed under: ${INSTALL_DIR}`.underline + ' 🎉'
}, )
async update() { },
checkIfResticIsAvailable() uninstall() {
const w = new Writer('Checking for latest restic version... ⏳') for (const bin of ['restic', 'autorestic'])
exec('restic', ['self-update']) try {
unlinkSync(INSTALL_DIR + '/' + bin)
console.log(`Finished! ${bin} was uninstalled`)
w.replaceLn('Checking for latest autorestic version... ⏳') } catch (e) {
const { data: json } = await axios({ console.log(`${bin} is already uninstalled`.red)
method: 'get', }
url: 'https://api.github.com/repos/cupcakearmy/autorestic/releases/latest', },
responseType: 'json', async update() {
}) checkIfResticIsAvailable()
const w = new Writer('Checking for latest restic version... ⏳')
if (json.tag_name != VERSION) { exec('restic', ['self-update'])
const platformMap: { [key: string]: string } = {
'darwin': 'macos', w.replaceLn('Checking for latest autorestic version... ⏳')
} const { data: json } = await axios({
method: 'get',
const name = `autorestic_${platformMap[process.platform] || process.platform}_${process.arch}` url:
const dl = json.assets.find((asset: any) => asset.name === name) 'https://api.github.com/repos/cupcakearmy/autorestic/releases/latest',
responseType: 'json',
const to = INSTALL_DIR + '/autorestic' })
w.replaceLn('Downloading binary... 🌎')
await downloadFile(dl.browser_download_url, to) if (json.tag_name != VERSION) {
const platformMap: { [key: string]: string } = {
exec('chmod', ['+x', to]) darwin: 'macos',
} }
w.done('All up to date! 🚀') const name = `autorestic_${platformMap[process.platform] ||
}, process.platform}_${process.arch}`
const dl = json.assets.find((asset: any) => asset.name === name)
const to = INSTALL_DIR + '/autorestic'
w.replaceLn('Downloading binary... 🌎')
await downloadFile(dl.browser_download_url, to)
exec('chmod', ['+x', to])
}
w.done('All up to date! 🚀')
},
} }
export const help = () => { export const help = () => {
console.log('\nAutorestic'.blue + ` - ${VERSION} - Easy Restic CLI Utility` console.log(
+ '\n' '\nAutorestic'.blue +
+ '\nOptions:'.yellow ` - ${VERSION} - Easy Restic CLI Utility` +
+ `\n -c, --config Specify config file. Default: ${CONFIG_FILE}` '\n' +
+ '\n' '\nOptions:'.yellow +
+ '\nCommands:'.yellow `\n -c, --config Specify config file. Default: .autorestic.yml` +
+ '\n check [-b, --backend] [-a, --all] Check backends' '\n' +
+ '\n backup [-l, --location] [-a, --all] Backup all or specified locations' '\nCommands:'.yellow +
+ '\n restore [-l, --location] [-- --target <out dir>] Check backends' '\n check [-b, --backend] [-a, --all] Check backends' +
+ '\n' '\n backup [-l, --location] [-a, --all] Backup all or specified locations' +
+ '\n exec [-b, --backend] [-a, --all] <command> -- [native options] Execute native restic command' '\n restore [-l, --location] [-- --target <out dir>] Restore all or specified locations' +
+ '\n' '\n' +
+ '\n install install restic' '\n exec [-b, --backend] [-a, --all] <command> -- [native options] Execute native restic command' +
+ '\n uninstall uninstall restic' '\n' +
+ '\n update update restic' '\n install install restic' +
+ '\n help Show help' '\n uninstall uninstall restic' +
+ '\n' '\n update update restic' +
+ '\nExamples: '.yellow + 'https://git.io/fjVbg' '\n help Show help' +
+ '\n', '\n' +
) '\nExamples: '.yellow +
'https://git.io/fjVbg' +
'\n'
)
} }
export const error = () => { export const error = () => {
help() help()
console.log(`Invalid Command:`.red.underline, `${process.argv.slice(2).join(' ')}`) console.log(
`Invalid Command:`.red.underline,
`${process.argv.slice(2).join(' ')}`
)
} }
export default handlers export default handlers
Loading…
Cancel
Save