Giter Site home page Giter Site logo

jonschlinkert / normalize-pkg Goto Github PK

View Code? Open in Web Editor NEW
18.0 3.0 2.0 179 KB

Normalize values in package.json to improve compatibility, programmatic readability and usefulness with third party libs.

Home Page: https://github.com/jonschlinkert

License: MIT License

JavaScript 100.00%
package json packagejson node nodejs javascript normalize schema object jonschlinkert

normalize-pkg's Introduction

normalize-pkg Donate NPM version NPM monthly downloads NPM total downloads Build Status

Normalize values in package.json using the map-schema library.

Please consider following this project's author, Jon Schlinkert, and consider starring the project to show your ❤️ and support.

Table of Contents

Details

Install

Install with npm (requires Node.js >= 0.10.0):

$ npm install --save normalize-pkg

Install

Install with bower

$ bower install normalize-pkg --save

Usage

var config = require('./')();
var pkg = config.normalize(require('./package'));

Features

Normalizes most package.json fields, and:

  • converts repository objects to a string
  • stringifies author object
  • stringifies each "person" object in maintainers, contributors and collaborators
  • converts licenses arrays and objects to a license string
  • removes files that don't exist from bin, main and the files array
  • adds cli.js to bin if it exists
  • creates keywords array from name if not defined

See the schema, normalizers, and unit tests for more examples.

Schema

Values are normalized using a schema that is passed to map-schema.

  • only properties that have a corresponding field on the schema will be normalized.
  • any properties that do not have a corresponding field are returned unmodified.

See the .field docs to learn how to add or overwrite a field on the schema.

Defaults

A default value may optionally be defined when a .field is registered. When .normalize is run and a property that is required or recommended by npm is missing, normalize-pkg attempts to create the field if valid data can be found in the repository.

built-in fields have a default value:

  • version: '0.1.0'
  • license: 'MIT'
  • engines: {node: '>= 0.10.0'}

For example:

  • name: the project-name library is used to fill in the name
  • bin: if empty, populated with cli.js or bin if either exists on the file system

Example

The following:

var config = require('./')();

// no package.json is passed, just an empty object
var pkg = config.normalize({});
console.log(pkg);

Results

Since an empty object was passed, normalize-pkg was smart enough to fill in missing fields looking for info in the project. In this case, specifically from parsing .git config and using any defaults defined on the schema.

{ name: 'normalize-pkg',
  version: '0.1.0',
  homepage: 'https://github.com/jonschlinkert/normalize-pkg',
  repository: 'jonschlinkert/normalize-pkg',
  license: 'MIT',
  files: [ 'index.js' ],
  main: 'index.js',
  engines: { node: '>= 0.10.0' } }

API

Params

  • options {Object}

Example

const config = new NormalizePkg();
const pkg = config.normalize({
  author: {
    name: 'Jon Schlinkert',
    url: 'https://github.com/jonschlinkert'
  }
});
console.log(pkg);
//=> {author: 'Jon Schlinkert (https://github.com/jonschlinkert)'}
  • normalize {Function}: function to be called on the value when the .normalize method is called
  • default {any}: default value to be used when the package.json property is undefined.
  • required {Boolean}: define true if the property is required

Params

  • name {String}: Field name (required)
  • type {String|Array}: One or more native javascript types allowed for the property value (required)
  • options {Object}
  • returns {Object}: Returns the instance

Example

const config = new NormalizePkg();

config.field('foo', 'string', {
  default: 'bar'
});

const pkg = config.normalize({});
console.log(pkg);
//=> {foo:  'bar'}

Params

  • pkg {Object}: The package.json object to normalize
  • options {Object}
  • returns {Object}: Returns a normalized package.json object.

Example

const config = new NormalizePkg();
const pkg = config.normalize(require('./package.json'));

Options

options.knownOnly

Type: boolean

Default: undefined

Omit properties from package.json that do not have a field registered on the schema.

var Config = require('normalize-pkg');
var config = new Config({knownOnly: true});

var pkg = config.normalize({name: 'my-project', foo: 'bar'});
console.log(pkg);
//=> {name: 'my-project'}

options.pick

Type: array

Default: undefined

Filter the resulting object to contain only the specified keys.

options.omit

Type: array

Default: undefined

Remove the specified keys from the resulting object.

options.fields

Pass a fields object on the options to customize any fields on the schema (also see options.extend):

var pkg = config.normalize(require('./package'), {
  extend: true,
  fields: {
    name: {
      normalize: function() {
        return 'bar'
      }
    }
  }
});

console.log(pkg.name);
//=> 'bar'

options.extend

Type: boolean

Default: undefined

Used with options.field, pass true if you want to extend a field that is already defined on the schema.

var pkg = config.normalize(require('./package'), {
  extend: true,
  fields: {
    name: {
      normalize: function() {
        return 'bar'
      }
    }
  }
});

console.log(pkg.name);
//=> 'bar'

About

Contributing

Pull requests and stars are always welcome. For bugs and feature requests, please create an issue.

Running Tests

Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command:

$ npm install && npm test
Building docs

(This project's readme.md is generated by verb, please don't edit the readme directly. Any changes to the readme must be made in the .verb.md readme template.)

To generate the readme, run the following command:

$ npm install -g verbose/verb#dev verb-generate-readme && verb

Related projects

You might also be interested in these projects:

update: Be scalable! Update is a new, open source developer framework and CLI for automating updates… more | homepage

Contributors

Commits Contributor
154 jonschlinkert
16 doowb
2 pdehaan

Author

Jon Schlinkert

License

Copyright © 2020, Jon Schlinkert. Released under the MIT License.


This file was generated by verb-generate-readme, v0.8.0, on March 01, 2020.

normalize-pkg's People

Contributors

doowb avatar jonschlinkert avatar pdehaan avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

Forkers

pdehaan bambidus

normalize-pkg's Issues

Support for repo shorthand syntax

Steps to reproduce

  1. Create a package.json file and set the repository to a shorthand GitHub "owner/repo" syntax:

    {
        "repository": "pdehaan/hapi-examples",
        "name": "normalize-pkg-test",
        "version": "1.0.0"
    }
  2. Run $ normalize

Actual results

{
  "repository": {
    "type": "",
    "url": "pdehaan/hapi-examples"
  },
  "name": "normalize-pkg-test",
  "version": "1.0.0",
  /* snip... */
}

Not sure if the shorthand is valid when using the longer object form of repository, or if you want to default the type to "git" and use something like robertkowalski/github-url-from-username-repo to expand the URL to longer form URL.

author fields not being parsed correctly

Steps to reproduce:

  1. $ touch index.js (optional)
  2. $ npm init (finish wizard, this step probably is a bit inconsistent based on your current npm config setup.)
  3. $ normalize

Actual results:

  "author": {
    "name": "Peter deHaan <[email protected]> (http://nodeexamples.com/)",
    "url": ""
  },

Expected results:

"author": {
  "name": "Peter deHaan",
  "url": "http://nodeexamples.com/",
  "email": "[email protected]"
},
...

move the CLI into a yeoman generator

This will allow users and implementors to get what they want from this lib.

  • make the logic in normalize-pkg more granular. e.g instead of adding flags for everything we can just expose an API for, say, normalizing from a string to an object, or vice versa
  • move the opinions to the generator and subgenerators
  • out of the box, the generator can create a new package.json using yo pkg
  • If a package.json already exists, the generator will normalize it using some agreed upon defaults

Subgenerators

Subgenerators will make it easy to generate a package.json that follows whatever standards you want. E.g. to generate a package.json that strictly adheres to npm standards, you would use the strict subgenerator with yo pkg:strict.

try to extract bug url from repository

... probably only works w/ GitHub URLs, but I think npm does this by default when creating a package.json file via npm init.

Before:

{
  "name": "pkg3",
  "version": "0.1.0-DEV",
  "description": "Foo baz",
  "repository": {
    "type": "git",
    "url": "[email protected]:jonschlinkert/normalize-pkg.git"
  },
  "licenses": [
    {
      "type": "GPL-2.0"
    }
  ]
}

After:

{
  "name": "pkg3",
  "version": "0.1.0-DEV",
  "description": "Foo baz",
  "repository": {
    "type": "git",
    "url": "[email protected]:jonschlinkert/normalize-pkg.git"
  },
  "licenses": [
    {
      "type": "GPL-2.0"
    }
  ],
  "author": {
    "name": "",
    "url": ""
  },
  "bugs": {
    "url": ""
  },
  "keywords": []
}

Expected

  "bugs": {
    "url": "https://github.com/jonschlinkert/normalize-pkg/issues/"
  },

This may help: https://github.com/visionmedia/node-github-url-from-git

Search for local LICENSE file?

More of an odd question rather than a bug...

I was looking through the inferLicenseURL() method and wasn't sure if you wanted to:

  1. Add "MPL" license (I'm biased here): http://www.mozilla.org/MPL/
  2. Search the local repo for a LICENSE file and link to that. This could be a bit mucky since it requires some OS filesystem stuff and then possibly trying to determine a fully qualified URL to said license.

I can split these out into separate GitHub issues if you want.

repository normalizer

This block is causing the repository value to be overwritten when it's already a string, which becomes an issue when the project name is scoped for use in npm.

Locally, I added a check to see if val is a string like the other if blocks and it seems to work. I'll submit a PR with tests when I have a chance but wanted to open this issue as a reminder.

store common, generic config values

Use configstore to populate missing fields with globally stored config values.

The CLI can prompt the user to ask if you want to use any of those fields.

Integrate package.json validator output?

Since this alters the package.json file quite a bit in some cases, not sure if you want to add some more debug output after rewriting the package.json file.

Relevant: https://github.com/gorillamania/package.json-validator

For example, after rewriting the package.json file, maybe just a brief few lines of output saying:

package.json file valid: false
errors:

  • bugs field should have one of: email, url, mail, web
  • licenses field should have url
  • author field should have name

module, like, goes crazy on empty package.json

Steps to reproduce:

  1. $ echo "{}" > package.json
  2. $ normalize
  3. $ cat package.json

Actual results:

{
  "author": {
    "name": "",
    "url": ""
  },
  "repository": {
    "type": "",
    "url": ""
  },
  "bugs": {
    "url": ""
  },
  "licenses": [
    {
      "type": "",
      "url": ""
    }
  ],
  "keywords": []
}

Expected results:

Simmer down, bro!

Running the newly normalized package.json through http://package-json-validator.com gives the following output:

{
  "valid": false,
  "errors": [
    "Missing required field: name",
    "Missing required field: version",
    "bugs field should have one of: email, url, mail, web",
    "licenses field should have type",
    "licenses field should have url",
    "author field should have name",
    "repository field should have type",
    "repository field should have url"
  ],
  "warnings": [
    "Missing recommended field: description",
    "Missing recommended field: contributors"
  ],
  "recommendations": [
    "Missing optional field: homepage",
    "Missing optional field: dependencies",
    "Missing optional field: engines"
  ]
}

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.