-
Notifications
You must be signed in to change notification settings - Fork 13
/
ButtercupCSVImporter.js
79 lines (74 loc) · 2.57 KB
/
ButtercupCSVImporter.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
const fs = require("fs/promises");
const { Group, Vault } = require("buttercup");
const csvparse = require("csv-parse/lib/sync");
const NON_COPY_KEYS = ["id", "title"];
/**
* Importer for Buttercup CSV exports
* @memberof module:ButtercupImporter
*/
class ButtercupCSVImporter {
/**
* Create a new Buttercup CSV importer
* @param {String} csvData Raw CSV data of a Buttercup vault export
*/
constructor(csvData) {
this._csvData = csvData;
}
/**
* Export to a Buttercup vault
* @returns {Promise.<Vault>}
* @memberof ButtercupCSVImporter
*/
export() {
return Promise.resolve().then(() => {
const vault = new Vault();
csvparse(this._csvData, { columns: true }).forEach((bcupItem) => {
const {
["!type"]: itemType,
["!group_id"]: groupID,
["!group_name"]: groupName,
["!group_parent"]: groupParentID,
} = bcupItem;
let group = vault.findGroupByID(groupID);
if (itemType === "group") {
if (!group) {
group = Group.createNew(vault, groupParentID, groupID);
}
group.setTitle(groupName);
} else if (itemType === "entry") {
if (!group) {
throw new Error(
`No group found for entry import: ${groupID}`
);
}
const entry = group.createEntry(bcupItem.title);
Object.keys(bcupItem)
.filter((key) => /^\!.+/.test(key) === false)
.filter((key) => NON_COPY_KEYS.indexOf(key) === -1)
.filter((key) => bcupItem[key])
.forEach((key) => {
entry.setProperty(key, bcupItem[key]);
});
} else {
throw new Error(
`Unrecognised item type in import: ${itemType}`
);
}
});
return vault;
});
}
}
/**
* Load CSV data from a file
* @param {String} filename The file to read (CSV)
* @returns {Promise.<ButtercupCSVImporter>}
* @memberof ButtercupCSVImporter
* @static
*/
ButtercupCSVImporter.loadFromFile = function (filename) {
return fs
.readFile(filename, "utf8")
.then((data) => new ButtercupCSVImporter(data));
};
module.exports = ButtercupCSVImporter;