UNPKG

2.7 kBPlain TextView Raw
1import { Bucket, getBucket } from 'cloud-bucket';
2import { pathExists } from 'fs-extra';
3import { loadYaml } from './utils';
4
5export type PathInfo = {
6 store: string,
7 path?: string, // path or glob
8}
9
10
11// --------- Public list/copy/del/download/upload --------- //
12export async function list(pathInfo: PathInfo) {
13 const bucket = await getBucketFromPathInfo(pathInfo);
14 const result = await bucket.listFiles(pathInfo.path);
15 return result;
16}
17
18export async function copy(from: PathInfo, to: PathInfo) {
19 const files = await list(from);
20 const destBucket = await getBucketFromPathInfo(to);
21 // FIXME: Need to be implemented
22}
23
24export async function download(from: PathInfo, destDir: string) {
25 if (from.path == null) {
26 throw new Error(`Cannot download - undefined remote path: ${from.store}:${from.path}`);
27 }
28 const bucket = await getBucketFromPathInfo(from);
29 return bucket.download(from.path, destDir);
30}
31
32export async function upload(localFile: string, dest: PathInfo) {
33 if (dest.path == null) {
34 throw new Error(`Cannot download - undefined remote path: ${dest.store}:${dest.path}`);
35 }
36 const bucket = await getBucketFromPathInfo(dest);
37 return bucket.upload(localFile, dest.path);
38}
39// --------- /Public list/cp/del/download/upload ------, --- //
40
41// --------- public PathInfo --------- //
42
43
44const formatInfo = `'storename:path' or just 'storename'`;
45
46export function parsePathInfo(storeAndPathStr?: string) {
47 if (storeAndPathStr == null || storeAndPathStr.length == 0) {
48 throw new Error(`gs need to have a path like ${formatInfo}`);
49 }
50 const storeAndPath = storeAndPathStr.split(':');
51 if (storeAndPath.length > 2) {
52 throw new Error(`Path ${storeAndPathStr} is invalid, needs to be of format like ${formatInfo}`)
53 }
54
55 const [store, path] = storeAndPath;
56
57 return { store, path };
58
59}
60// --------- /public PathInfo --------- //
61
62
63// --------- Private Utils --------- //
64
65async function getBucketFromPathInfo(pathInfo: PathInfo): Promise<Bucket> {
66 const bucketCfgs = await loadRawBucketsConfig();
67
68 const rawCfg = bucketCfgs?.[pathInfo.store];
69 if (rawCfg == null) {
70 throw new Error('VDEV ERROR - cannot find bucket ${pathInfo.store} in .vdev-buckets.yaml file');
71 }
72 return getBucket({ ...rawCfg, log: true });
73
74}
75
76
77async function loadRawBucketsConfig() {
78 const files = ['.vdev-buckets.yaml', 'vdev-buckets.yaml'];
79 let vdevBuckets: any;
80 for (const file of files) {
81 if (await pathExists(file)) {
82 vdevBuckets = await loadYaml(file);
83 break;
84 }
85 }
86 if (vdevBuckets != null) {
87 const confs = vdevBuckets.buckets;
88 // add the .name to each bucket info
89 for (let name in confs) {
90 confs[name].name = name;
91 }
92 return confs;
93 }
94}
95
96// --------- /Private Utils --------- //
\No newline at end of file