Skip to content

Commit

Permalink
Improve the error message when the YAML file is malformed
Browse files Browse the repository at this point in the history
  • Loading branch information
darekkay committed May 23, 2024
1 parent 6dfc452 commit 2617d8a
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
## [Unreleased]

- :boom: Drop Node 16 support (EOL).
- :rocket: Improve the error message when the YAML file is malformed ([#47]).
- :hammer: Switch from yarn to npm.
- :book: Add a troubleshooting section ([#46]).

Expand Down Expand Up @@ -166,6 +167,7 @@
[#30]: https://github.com/darekkay/static-marks/issues/30
[#33]: https://github.com/darekkay/static-marks/issues/33
[#46]: https://github.com/darekkay/static-marks/issues/46
[#47]: https://github.com/darekkay/static-marks/issues/47

---

Expand Down
19 changes: 18 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,22 @@ const transform = require("./transform-json");
const render = require("./render");
const { writeFile } = require("./utils");

/** Validate each level of a bookmarks YAML file. */
const validateBookmarkStructure = (bookmarks) => {
if (bookmarks === undefined) throw new Error(" - YAML file is empty.");
if (Array.isArray(bookmarks)) throw new Error(" - First level must be an object, not a list.");

Object.entries(bookmarks).forEach(([key, values]) => {
if (!Array.isArray(values)) throw new Error(` - Collection '${key}' must be a list of buckets.`)

values.forEach((bucket) => {
Object.entries(bucket).forEach(([bucketKey, bucketValues]) => {
if (!Array.isArray(bucketValues)) throw new Error(` - Bucket '${bucketKey}' must be a list of bookmarks.`)
})
})
})
}

const build = (files, config) => {
const template = fs.readFileSync(config.templateFilePath, "utf8");

Expand All @@ -16,6 +32,7 @@ const build = (files, config) => {
.map((file) => {
try {
const json = yaml.load(fs.readFileSync(file, "utf8"));
validateBookmarkStructure(json);
return {
key: path.basename(file, ".yml"),
collections: transform(json),
Expand All @@ -31,7 +48,7 @@ const build = (files, config) => {
.filter((bookmark) => bookmark !== undefined);

if (loadFailed) {
logger.error("Process aborted: at least one YAML file is malformed.");
logger.error("Process aborted: at least one YAML file is malformed. Read the project documentation for the correct file format.");
process.exit(1);
}

Expand Down

0 comments on commit 2617d8a

Please sign in to comment.