Git Product home page Git Product logo

mrm-core's Introduction

.

.

.

.

.

.

npm Build Status Codecov

Utilities to write codemods for config files (JSON, YAML, INI, Markdown, etc.). Can be used to make tasks for Mrm.

Table of contents

Example

Add ESLint to your project:

const { json, lines, packageJson, install } = require('mrm-core')

module.exports = function(config) {
  const preset = config('preset', 'tamia')
  const packages = ['eslint', `eslint-config-${preset}`]

  // .eslintrc
  const eslintrc = json('.eslintrc')
  if (!eslintrc.get('extends').startsWith(preset)) {
    eslintrc.set('extends', preset).save()
  }

  // .eslintignore
  lines('.eslintignore')
    .add('node_modules')
    .save()

  // package.json
  const pkg = packageJson()
    .setScript('lint', 'eslint . --fix')
    .setScript('pretest', 'npm run line')
    .save()

  // Install dependencies
  install(packages)
}
module.exports.description = 'Adds ESLint with a custom preset'

Read more in mrm’s docs, and this task is already included by default.

You can find more examples here.

You don’t have to use mrm-core with mrm, you can run this tasks from your own code:

const get = require('lodash/get')
const addEslint = require('./tasks/eslint')
const config = {
  preset: 'airbnb'
}
const getConfig = (prop, defaultValue) =>
  get(config, prop, defaultValue)
addEslint(getConfig)

Installation

npm install --save-dev mrm-core

API

Work with files

  • Do not overwrite original files, unless you want to.
  • All functions (except getters) can be chained.
  • save() will create file if it doesn’t exist or update it with new data.
  • save() will write file to disk only if the new content is different from the original file.
  • save() will try to keep formatting (indentation, end of file new line) of the original file or use style from EditorConfig.

JSON

API:

const { json } = require('mrm-core')
const file = json('file name', { default: 'values' })
file.exists() // File exists?
file.get() // Return everything
file.get('key.subkey', 'default value') // Return value with given address
file.set('key.subkey', 'value') // Set value by given address
file.set({ key: value }) // Replace JSON with given object
file.unset('key.subkey') // Remove value by given address
file.merge({ key: value }) // Merge JSON with given object
file.save() // Save file
file.delete() // Delete file

Example:

json('.eslintrc')
  .merge({
    extends: 'eslint-config-recommended'
  })
  .save()

YAML

API:

const { yaml } = require('mrm-core')
const file = yaml('file name', { default: 'values' })
file.exists() // File exists?
file.get() // Return everything
file.get('key.subkey', 'default value') // Return value with given address
file.set('key.subkey', 'value') // Set value by given address
file.set({ key: value }) // Replace JSON with given object
file.unset('key.subkey') // Remove value by given address
file.merge({ key: value }) // Merge JSON with given object
file.save() // Save file
file.delete() // Delete file

Example:

yaml('.travis.yml')
  .set('language', 'node_js')
  .set('node_js', [4, 6])
  .save()

INI

API:

const { ini } = require('mrm-core')
const file = ini('file name', 'comment')
file.exists() // File exists?
file.get() // Return everything
file.get('section name') // Return section value
file.set('section name', { key: value }) // Set section value
file.unset('section name') // Remove section
file.save() // Save file
file.save({ withSpaces: false }) // Disable spaces around =
file.delete() // Delete file

Example:

const { ini } = require('mrm-core')
ini('.editorconfig', 'editorconfig.org')
  .set('_global', { root: true })
  .set('*', {
    indent_style: 'tab',
    end_of_line: 'lf'
  })
  .save()

Result:

# editorconfig.org
root = true

[*]
indent_style = tab
end_of_line = lf

New line separated text files

API:

const { lines } = require('mrm-core')
const file = lines('file name', ['default', 'values'])
file.exists() // File exists?
file.get() // Return everything
file.set(['line 1', 'line 2', 'line 3']) // Set file lines, overwrite existing
file.add('new') // Add new line
file.add(['new', 'lines']) // Add multiple news lines
file.remove('new') // Remove line
file.remove(['new', 'lines']) // Remove multiple lines
file.save() // Save file
file.delete() // Delete file

Example:

lines('.eslintignore')
  .add('node_modules')
  .save()

Markdown

Note: use template function to create Markdown files.

API:

const { markdown } = require('mrm-core')
const file = markdown('file name')
file.exists() // File exists?
file.get() // Return file content
file.addBadge('image URL', 'link URL', 'alt text') // Add a badge at the beginning of the file (below header)
file.save() // Save file
file.delete() // Delete file

Example:

const name = 'pizza'
markdown('Readme.md')
  .addBadge(
    `https://travis-ci.org/${config('github')}/${name}.svg`,
    `https://travis-ci.org/${config('github')}/${name}`,
    'Build Status'
  )
  .save()

Plain text templates

Templates use ECMAScript template literals syntax.

API:

const { template } = require('mrm-core')
const file = template('file name', 'template file name')
file.exists() // File exists?
file.get() // Return file content
file.apply({ key: 'value' }) // Replace template tags with given values
file.save() // Save file
file.delete() // Delete file

Example:

template('License.md', path.join(__dirname, 'License.md'))
  .apply(config(), {
    year: new Date().getFullYear()
  })
  .save()

Template:

The MIT License
===============

Copyright ${year} ${name} (${url}), contributors

Permission is hereby granted, free of charge, to any person obtaining...

Special files

package.json

API:

const { packageJson } = require('mrm-core')
const file = packageJson({ default: 'values' })
file.exists() // File exists?
file.get() // Return everything
file.getScript('test') // Return script
file.getScript('test', 'eslint') // Return a subcommand of a script
file.setScript('test', 'eslint --fix') // Replace a script with a command: a -> b
file.appendScript('test', 'eslint --fix') // Append command to a script: a -> a && b
file.prependScript('test', 'eslint --fix') // Prepend a script with a command: a -> b && a
file.removeScript('test') // Remove script
file.removeScript(/^mocha|ava$/) // Remove all scripts that match a regexp
file.removeScript('test', /b/) // Remove subcommands from a script: a && b -> a
file.save() // Save file
file.delete() // Delete file
// All methods of json() work too

Note: subcommand is a command between && in an npm script. For example, prettier --write '**/*.js' && eslint . --fix has two subcommands: prettier… and eslint….

Example:

packageJson()
  .appendScript('lint', 'eslint . --ext .js --fix')
  .save()

File system helpers

const { copyFiles, deleteFiles, makeDirs } = require('mrm-core')
copyFiles('source dir', 'file name') // Copy file
copyFiles('source dir', ['file name 1', 'file name 2']) // Copy files
copyFiles('source dir', 'file name', { overwrite: false }) // Do not overwrite
deleteFiles('file name 1') // Delete file or folder
deleteFiles(['file name 1', 'folder name 1']) // Delete files or folders
makeDirs('dir name') // Create folder
makeDirs(['dir name 1', 'dir name 2']) // Create folders

Install and uninstall npm or Yarn packages

Installs npm package(s) and saves them to package.json if they aren’t installed yet or not satisfying range.

const { install } = require('mrm-core')
install('eslint') // Install to devDependencies
install(['tamia', 'lodash'], { dev: false }) // Install to dependencies
install({ lodash: '^4.17.3' }) // Install particular version
install(['lodash'], {
  versions: { lodash: '^4.17.3', other: '1.0.0' }
}) // Install particular version

Note: Works with all semver ranges, like 1.2.3, ^1.2.0 or >=2.

Uninstalls npm package(s) and removes them from package.json:

const { uninstall } = require('mrm-core')
uninstall('eslint') // Uninstall from devDependencies
uninstall(['tamia', 'lodash'], { dev: false }) // Uninstall from dependencies

To use Yarn pass yarn: true:

const { install, uninstall } = require('mrm-core')

uninstall(['eslint'], { yarn: true })
install(['standard'], { yarn: true })

Utilities

Infers style (indentation, new line at the end of file) from a source code or reads from the .editorconfig file.

const {
  inferStyle,
  getStyleForFile,
  getIndent,
  format
} = require('mrm-core')
inferStyle('for (;;) {\n  alert(1);\n}\n')
// => { insert_final_newline: true, indent_style: 'space', indent_size: 2 }
getStyleForFile('test.js')
// => { insert_final_newline: false, indent_style: 'tab', indent_size: 'tab' }
getIndent({ indent_style: 'space', indent_size: 2 })
// => '  '
format('alert(1)\n', { insert_final_newline: false })
// => 'alert(1)'
// Only insert_final_newline is supported

Get file extensions list from a command like eslint . --fix --ext .js,.jsx:

const { getExtsFromCommand } = require('mrm-core')
getExtsFromCommand(`eslint . --fix --ext .js,.jsx`, 'ext')
// => ['js', 'jsx']
getExtsFromCommand(`prettier --write '**/*.js'`)
// => ['js']

Custom error class: MrmError

Use this class to notify user about expected errors in your tasks. It will be printed without a stack trace and will abort task.

const { MrmError } = require('mrm-core')
if (!fs.existsSync('.travis.yml')) {
  throw new MrmError('Run travis task first')
}

Change log

The change log can be found on the Releases page.

Contributing

Everyone is welcome to contribute. Please take a moment to review the contributing guidelines.

Authors and license

Artem Sapegin and contributors.

MIT License, see the included License.md file.

mrm-core's People

Contributors

aleung avatar dependabot[bot] avatar fredyc avatar lukeed avatar marsup avatar noxan avatar npirotte avatar oieduardorabelo avatar romainlanz avatar sapegin avatar targos avatar thetutlage avatar trysound avatar

Stargazers

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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

mrm-core's Issues

[email protected] breaks test case

Package defines "memfs": "^2.6.0".

If ignore package-lock.json, latest [email protected] will be installed. Test cases fail with [email protected]:

 FAIL  src/files/__tests__/packageJson.spec.js
  ● packageJson() › should create package.json file

    expect(value).toMatchSnapshot()

    Received value does not match stored snapshot 1.

    - Snapshot
    + Received

      Object {
    +   "/": null,
        "/package.json": "{}",
      }

      at Object.it (src/files/__tests__/packageJson.spec.js:37:24)
          at new Promise (<anonymous>)
          at <anonymous>
      at process._tickCallback (../../../../../internal/process/next_tick.js:188:7)

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this 💪.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


Invalid npm token.

The npm token configured in the NPM_TOKEN environment variable must be a valid token allowing to publish to the registry https://registry.npmjs.org/.

If you are using Two-Factor Authentication, make configure the auth-only level is supported. semantic-release cannot publish with the default auth-and-writes level.

Please make sure to set the NPM_TOKEN environment variable in your CI with the exact value of the npm token.


Good luck with your project ✨

Your semantic-release bot 📦🚀

mrm/src/index.js throws "module is not a function" error

With the directory structure...

.mrm
├── config.json
├── editorconfig
│   └── index.js
├── package.json
└── yarn.lock

... and editorconfig/index.js consisting of (the example from this repo):

const { ini } = require('mrm-core')
ini('.editorconfig', 'editorconfig.org')
  .set('_global', { root: true })
  .set('*', {
    indent_style: 'tab',
    end_of_line: 'lf',
  })
  .save()

I get the .editorconfig I would expect as output—but, with the following error:

👻 ➜  .mrm git:(master) ✗ mrm editorconfig
Running editorconfig...
Create .editorconfig
/Users/me/.config/yarn/global/node_modules/mrm/bin/mrm.js:36
                throw err;
                ^

TypeError: module is not a function
    at /Users/me/.config/yarn/global/node_modules/mrm/src/index.js:136:19
    at new Promise (<anonymous>)
    at runTask (/Users/me/.config/yarn/global/node_modules/mrm/src/index.js:121:9)
    at run (/Users/me/.config/yarn/global/node_modules/mrm/src/index.js:81:9)
    at /Users/me/.config/yarn/global/node_modules/mrm/src/index.js:71:12
    at /Users/me/.config/yarn/global/node_modules/mrm/src/index.js:55:30

Utils to work with npm script

replaceScript

{
  "scripts": {
     "test": "npm run test:jest"
  }
}

// replaceScript('test', 'npm run lint')
{
  "scripts": {
     "test": "npm run lint"
  }
}

prependScript

{
  "scripts": {
     "test": "npm run test:jest"
  }
}

// prependScript('test', 'npm run lint')
{
  "scripts": {
     "test": "npm run lint && npm run lint"
  }
}

appendScript

{
  "scripts": {
     "test": "npm run test:jest"
  }
}

// appendScript('test', 'npm run lint')
{
  "scripts": {
     "test": "npm run lint && npm run lint"
  }
}

YML files are changed with updated formatting

When I tried the simple script with updating .travis.yml file, I've got many formatting changes which are pretty annoying.

So the script could be like this

const { yaml } = require('mrm-core');

function task() {
  yaml('.travis.yml')
    .merge({ 'before_script': [
      './cc-test-reporter before-build'
    ]})
    .save();
};

task.description = 'Update CodeClimate usage on Travis CI';
module.exports = task;

And a result I have:

  1. removed spaces for key-value pairs, e.g. provider: <5 spaces> s3 --> provider:<1 space> s3
  2. appended quotes. e.g. on: --> 'on':
  3. removed comments, e.g. # also update .node_version -->

Is it possible to quickly update the YML parser at the project to mitigate this side-effects?
Thanks!

Make prettify of ini configurable

I was curious if there is a chance of making the prettify step within the save function of ini files configurable?

This is how I would imagine the api.

ini('file.ini').save({ prettify: false });

I would be willing to implement, just asking ahead not to waste time.

PS. Thanks so much for this awesome project :)

The check for pre and post scripts skips prePublishOnly

The code on this line checks for the base script to exist, when creating pre and post scripts.

However, scripts like prePublishOnly can exists, without publishOnly.

Do you think we should maintain a list of whitelisted scripts or remove the check for base script to exist?

Accepting filePath in `packageJson`

All file related API's accepts the argument to the define file name/path.

json('foo.json')

If the path is absolute, then it simply writes to that absolute path, which silently opens up the possibility to write contents to different directory by passing absolute paths.

json(join(someBasePath, 'foo.json'))

However, this is not possible with the packageJson file. Do you think, we can accept the 2nd argument as the filePath?

ini: fail to set key into global section

The file generated by example of ini misses the line root = true. This line is never generated by editorconfig neither.

const { ini } = require('mrm-core');
ini('.editorconfig', 'editorconfig.org')
  .set('root', true)
  .set('*', {
    indent_style: 'tab',
    end_of_line: 'lf'
  })
  .save();

Run all tasks flag

Hey hey. Would love to have a flag added that would run all tasks available. Perhaps --all?

Make install @latest optionnal

Despite the install method is very handy, I found the version management a bit too restrictive.
It's nice to install latest, but it would be really nice to be able to specify a range to be able to install specific version / version range into a project.

Currently that "latest only" makes ht feature unusable for my use case and I ll have to rewrite this myself...

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.