Coder Social home page Coder Social logo

metalsmith / default-values Goto Github PK

View Code? Open in Web Editor NEW
12.0 3.0 4.0 786 KB

Metalsmith Plugin for setting default values to file metadata

License: GNU Lesser General Public License v3.0

JavaScript 95.94% TypeScript 4.06%
metalsmith nodejs metalsmith-plugin default-values

default-values's Introduction

@metalsmith/default-values

A Metalsmith plugin for setting default values to file metadata.

metalsmith: core plugin npm: version ci: build code coverage license: LGPL-3.0

Features

  • sets default values for metadata keys and file contents on files matched by pattern
  • does not overwrite or transform key values that are already defined, unless strategy: 'overwrite'.
  • can set computed defaults based on other file keys or metalsmith metadata

Installation

NPM:

npm install @metalsmith/default-values

Yarn:

yarn add @metalsmith/default-values

Usage:

Pass @metalsmith/default-values to metalsmith.use:

import defaultValues from '@metalsmith/default-values'

// single defaults set for all HTML and markdown files
metalsmith.use({
  defaults: {
    pattern: '**/*.md',
    title: 'Lorem ipsum'
  }
})

metalsmith.use(
  defaultValues([
    {
      pattern: 'posts/*.md',
      defaults: {
        layout: 'post.hbs',
        date: function (post) {
          return post.stats.ctime
        }
      }
    },
    {
      pattern: 'diary/*.md',
      defaults: {
        layout: 'diary.hbs',
        private: true
      }
    },
    {
      pattern: ['diary/*.md', 'archive/**/*.md'],
      defaults: {
        no_index: true
      }
    },
    {
      pattern: '**/*.md',
      defaults: {
        layout: 'default.hbs'
      }
    }
  ])
)

Options

@metalsmith/default-values takes an array of defaults sets or a single defaults set. The defaults set has the following properties:

  • pattern (string|string[]): One or more glob patterns to match file paths. Defaults to '**' (all).
  • defaults (Object<string, any>): An object whose key-value pairs will be added to file metadata. You can also specify a function callback(file, metadata) to set dynamic defaults based on existing file or global metadata.
  • strategy ('keep'|'overwrite'): Strategy to handle setting defaults to keys that are aleady defined.

Examples

Setting defaults at a keypath

You can set a default at a file's nested keypath:

metalsmith.use(
  defaultValues({
    pattern: '**/*.md',
    pubdate(file) { return new Date() }
    'config.scripts.app': '/app.js',
  })
)

Setting default contents

You can set a file's default contents (which is a Node buffer) and any other Buffer properties:

metalsmith.use(
  defaultValues({
    pattern: '**/*.md',
    strategy: 'overwrite',
    contents: Buffer.from('TO DO')
  })
)

When using a JSON config, a string can be used as default and it will automatically be transformed into a buffer.

Setting dynamic defaults

You can set dynamic defaults based on current file metadata or metalsmith metadata:

metalsmith
  .metadata({
    build: { timestamp: Date.now() }
  })
  .use(
    defaultValues([
      {
        strategy: 'overwrite',
        defaults: {
          buildInfo(file, metadata) {
            return metadata.build
          },
          excerpt(file) {
            return file.contents.toString().slice(0, 200)
          }
        }
      }
    ])
  )

Combining with other plugins

@metalsmith/default-values works great with other @metalsmith plugins. The example below attaches a collection and layout matching the parent directory for all files in the directories services,products, and articles:

import slugify from 'slugify'
const contentTypes = ['product', 'service', 'article']

metalsmith
  .use(
    defaultValues(
      contentTypes.map((contentType) => ({
        pattern: `${contentType}s/*.md`, // pluralized
        defaults: {
          collection: `${contentType}s`, // pluralized
          bodyClass: contentType,
          layout: `${contentType}.njk`, // using jstransformer-nunjucks
          contentLength(file) {
            if (file.contents) return file.contents.toString().length
            return 0
          }
        }
      }))
    )
  )
  .use(markdown()) // @metalsmith/markdown
  .use(collections()) // @metalsmith/collections
  .use(
    layouts({
      // @metalsmith/layouts
      pattern: '**/*.html'
    })
  )

Debug

To enable debug logs, set the DEBUG environment variable to @metalsmith/default-values*:

metalsmith.env('DEBUG', '@metalsmith/default-values*')

Alternatively you can set DEBUG to @metalsmith/* to debug all Metalsmith core plugins.

CLI usage

To use this plugin with the Metalsmith CLI, add @metalsmith/default-values to the plugins key in your metalsmith.json file:

{
  "plugins": [
    {
      "@metalsmith/default-values": [
        {
          "pattern": "diary/*.md",
          "defaults": {
            "layout": "diary.hbs",
            "private": true
          }
        }
      ]
    }
  ]
}

License

LGPL-3.0 or later

default-values's People

Contributors

greenkeeper[bot] avatar kolektiv avatar seinolab avatar webketje avatar woodyrew avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

default-values's Issues

Integrate with metalsmith-collections

It would extremely useful if the very excellent metalsmith-default-values could utilise collections defined by metalsmith-collections.

At the moment I am writing:

    .use(collections({
        posts: {
          pattern: ['posts/*.md', '!posts/index.md'],
          sortBy: 'date',
          reverse: true
        }
    }))
    .use(defaultvals([
        {
            pattern: ['posts/*.md', '!posts/index.md'],
            defaults: {
                layout: 'post.njk'
            }
        }
    ]))

This means that I'm matching against posts twice in the build file.

It would be great if I could do something like:

    .use(collections({
        posts: {
          pattern: ['posts/*.md', '!posts/index.md'],
          sortBy: 'date',
          reverse: true
        }
    }))
    .use(defaultvals([
        {
            match: { collection: 'posts' }, // Use a previously defined collection here
            defaults: {
                layout: 'post.njk'
            }
        }
    ]))

While this might seem unnecessary in this short simple example, it would become more useful in more advanced build chains.

An example of a module using match in this way is metalsmith-permalinks.

I hope this issue is useful and can inspire further great development! ❀️

Fix typo in readme

change var default_values = require('metalsmith-default_values');
to var default_values = require('metalsmith-default-values');

metalsmith.match() issue with metalsmith-branch

Something I've noticed in my own plugins @webketje is how metalsmith-branch will only pass a subset of files to a child plugin, but if you use metalsmith.match() it will match against the "global" list of files, and you will end up with some filenames that might not be in your "working" file list.

The fix is using metalsmith.match(pattern, Object.keys(files)) in every plugin, like this: https://github.com/emmercm/metalsmith-reading-time/pull/88/files#diff-92bbac9a308cd5fcf9db165841f2d90ce981baddcb2b1e26cfff170929af3bd1R16

An in-range update of debug is breaking the build 🚨

Version 3.2.0 of debug was just published.

Branch Build failing 🚨
Dependency debug
Current Version 3.1.0
Type dependency

This version is covered by your current version range and after updating it in your project the build failed.

debug is a direct dependency of this project, and it is very likely causing it to break. If other packages depend on yours, this update is probably also breaking those in turn.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build failed (Details).

Release Notes 3.2.0

A long-awaited release to debug is available now: 3.2.0.

Due to the delay in release and the number of changes made (including bumping dependencies in order to mitigate vulnerabilities), it is highly recommended maintainers update to the latest package version and test thoroughly.


Minor Changes

Patches

Credits

Huge thanks to @DanielRuf, @EirikBirkeland, @KyleStay, @Qix-, @abenhamdine, @alexey-pelykh, @DiegoRBaquero, @febbraro, @kwolfy, and @TooTallNate for their help!

Commits

The new version differs by 25 commits.

There are 25 commits in total.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.