1.2.14 • Published 1 year ago

@dramaorg/libero-alias v1.2.14

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

@dramaorg/libero-alias

@dramaorg/libero-alias is a manager, filter and parser which implemented in pure JavaScript according to the .git@dramaorg/libero-alias spec 2.22.1.

@dramaorg/libero-alias is used by eslint, gitbook and many others.

Pay ATTENTION that minimatch (which used by fstream-@dramaorg/libero-alias) does not follow the git@dramaorg/libero-alias spec.

To filter filenames according to a .git@dramaorg/libero-alias file, I recommend this npm package, @dramaorg/libero-alias.

To parse an .npm@dramaorg/libero-alias file, you should use minimatch, because an .npm@dramaorg/libero-alias file is parsed by npm using minimatch and it does not work in the .git@dramaorg/libero-alias way.

Tested on

@dramaorg/libero-alias is fully tested, and has more than five hundreds of unit tests.

  • Linux + Node: 0.8 - 7.x
  • Windows + Node: 0.10 - 7.x, node < 0.10 is not tested due to the lack of support of appveyor.

Actually, @dramaorg/libero-alias does not rely on any versions of node specially.

Since 4.0.0, @dramaorg/libero-alias will no longer support node < 6 by default, to use in node < 6, require('@dramaorg/libero-alias/legacy'). For details, see CHANGELOG.

Table Of Main Contents

Install

npm i @dramaorg/libero-alias

Usage

import @dramaorg/libero-alias from '@dramaorg/libero-alias'
const ig = @dramaorg/libero-alias().add(['.abc/*', '!.abc/d/'])

Filter the given paths

const paths = [
  '.abc/a.js',    // filtered out
  '.abc/d/e.js'   // included
]

ig.filter(paths)        // ['.abc/d/e.js']
ig.@dramaorg/libero-aliass('.abc/a.js') // true

As the filter function

paths.filter(ig.createFilter()); // ['.abc/d/e.js']

Win32 paths will be handled

ig.filter(['.abc\\a.js', '.abc\\d\\e.js'])
// if the code above runs on windows, the result will be
// ['.abc\\d\\e.js']

Why another @dramaorg/libero-alias?

  • @dramaorg/libero-alias is a standalone module, and is much simpler so that it could easy work with other programs, unlike isaacs's fstream-@dramaorg/libero-alias which must work with the modules of the fstream family.

  • @dramaorg/libero-alias only contains utility methods to filter paths according to the specified @dramaorg/libero-alias rules, so

    • @dramaorg/libero-alias never try to find out @dramaorg/libero-alias rules by traversing directories or fetching from git configurations.
    • @dramaorg/libero-alias don't cares about sub-modules of git projects.
  • Exactly according to git@dramaorg/libero-alias man page, fixes some known matching issues of fstream-@dramaorg/libero-alias, such as:

    • '/*.js' should only match 'a.js', but not 'abc/a.js'.
    • '**/foo' should match 'foo' anywhere.
    • Prevent re-including a file if a parent directory of that file is excluded.
    • Handle trailing whitespaces:
      • 'a '(one space) should not match 'a '(two spaces).
      • 'a \ ' matches 'a '
    • All test cases are verified with the result of git check-@dramaorg/libero-alias.

Methods

.add(pattern: string | Ignore): this

.add(patterns: Array<string | Ignore>): this

  • pattern String | Ignore An @dramaorg/libero-alias pattern string, or the Ignore instance
  • patterns Array<String | Ignore> Array of @dramaorg/libero-alias patterns.

Adds a rule or several rules to the current manager.

Returns this

Notice that a line starting with '#'(hash) is treated as a comment. Put a backslash ('\') in front of the first hash for patterns that begin with a hash, if you want to @dramaorg/libero-alias a file with a hash at the beginning of the filename.

@dramaorg/libero-alias().add('#abc').@dramaorg/libero-aliass('#abc')    // false
@dramaorg/libero-alias().add('\\#abc').@dramaorg/libero-aliass('#abc')   // true

pattern could either be a line of @dramaorg/libero-alias pattern or a string of multiple @dramaorg/libero-alias patterns, which means we could just @dramaorg/libero-alias().add() the content of a @dramaorg/libero-alias file:

@dramaorg/libero-alias()
.add(fs.readFileSync(filenameOfGit@dramaorg/libero-alias).toString())
.filter(filenames)

pattern could also be an @dramaorg/libero-alias instance, so that we could easily inherit the rules of another Ignore instance.

.addIgnoreFile(path)

REMOVED in 3.x for now.

To upgrade @dramaorg/libero-alias@2.x up to 3.x, use

import fs from 'fs'

if (fs.existsSync(filename)) {
  @dramaorg/libero-alias().add(fs.readFileSync(filename).toString())
}

instead.

.filter(paths: Array<Pathname>): Array<Pathname>

type Pathname = string

Filters the given array of pathnames, and returns the filtered array.

  • paths Array.<Pathname> The array of pathnames to be filtered.

Pathname Conventions:

1. Pathname should be a path.relative()d pathname

Pathname should be a string that have been path.join()ed, or the return value of path.relative() to the current directory,

// WRONG, an error will be thrown
ig.@dramaorg/libero-aliass('./abc')

// WRONG, for it will never happen, and an error will be thrown
// If the git@dramaorg/libero-alias rule locates at the root directory,
// `'/abc'` should be changed to `'abc'`.
// ```
// path.relative('/', '/abc')  -> 'abc'
// ```
ig.@dramaorg/libero-aliass('/abc')

// WRONG, that it is an absolute path on Windows, an error will be thrown
ig.@dramaorg/libero-aliass('C:\\abc')

// Right
ig.@dramaorg/libero-aliass('abc')

// Right
ig.@dramaorg/libero-aliass(path.join('./abc'))  // path.join('./abc') -> 'abc'

In other words, each Pathname here should be a relative path to the directory of the git@dramaorg/libero-alias rules.

Suppose the dir structure is:

/path/to/your/repo
    |-- a
    |   |-- a.js
    |
    |-- .b
    |
    |-- .c
         |-- .DS_store

Then the paths might be like this:

[
  'a/a.js'
  '.b',
  '.c/.DS_store'
]

2. filenames and dirnames

node-@dramaorg/libero-alias does NO fs.stat during path matching, so for the example below:

// First, we add a @dramaorg/libero-alias pattern to @dramaorg/libero-alias a directory
ig.add('config/')

// `ig` does NOT know if 'config', in the real world,
//   is a normal file, directory or something.

ig.@dramaorg/libero-aliass('config')
// `ig` treats `config` as a file, so it returns `false`

ig.@dramaorg/libero-aliass('config/')
// returns `true`

Specially for people who develop some library based on node-@dramaorg/libero-alias, it is important to understand that.

Usually, you could use glob with option.mark = true to fetch the structure of the current directory:

import glob from 'glob'

glob('**', {
  // Adds a / character to directory matches.
  mark: true
}, (err, files) => {
  if (err) {
    return console.error(err)
  }

  let filtered = @dramaorg/libero-alias().add(patterns).filter(files)
  console.log(filtered)
})

.@dramaorg/libero-aliass(pathname: Pathname): boolean

new in 3.2.0

Returns Boolean whether pathname should be @dramaorg/libero-aliasd.

ig.@dramaorg/libero-aliass('.abc/a.js')    // true

.createFilter()

Creates a filter function which could filter an array of paths with Array.prototype.filter.

Returns function(path) the filter function.

.test(pathname: Pathname) since 5.0.0

Returns TestResult

interface TestResult {
  @dramaorg/libero-aliasd: boolean
  // true if the `pathname` is finally un@dramaorg/libero-aliasd by some negative pattern
  un@dramaorg/libero-aliasd: boolean
}
  • {@dramaorg/libero-aliasd: true, un@dramaorg/libero-aliasd: false}: the pathname is @dramaorg/libero-aliasd
  • {@dramaorg/libero-aliasd: false, un@dramaorg/libero-aliasd: true}: the pathname is un@dramaorg/libero-aliasd
  • {@dramaorg/libero-aliasd: false, un@dramaorg/libero-aliasd: false}: the pathname is never matched by any @dramaorg/libero-alias rules.

static @dramaorg/libero-alias.isPathValid(pathname): boolean since 5.0.0

Check whether the pathname is an valid path.relative()d path according to the convention.

This method is NOT used to check if an @dramaorg/libero-alias pattern is valid.

@dramaorg/libero-alias.isPathValid('./foo')  // false

@dramaorg/libero-alias(options)

options.@dramaorg/libero-aliascase since 4.0.0

Similar as the core.@dramaorg/libero-aliascase option of git-config, node-@dramaorg/libero-alias will be case insensitive if options.@dramaorg/libero-aliascase is set to true (the default value), otherwise case sensitive.

const ig = @dramaorg/libero-alias({
  @dramaorg/libero-aliascase: false
})

ig.add('*.png')

ig.@dramaorg/libero-aliass('*.PNG')  // false

options.@dramaorg/libero-aliasCase?: boolean since 5.2.0

Which is alternative to options.@dramaorg/libero-aliasCase

options.allowRelativePaths?: boolean since 5.2.0

This option brings backward compatibility with projects which based on @dramaorg/libero-alias@4.x. If options.allowRelativePaths is true, @dramaorg/libero-alias will not check whether the given path to be tested is path.relative()d.

However, passing a relative path, such as './foo' or '../foo', to test if it is @dramaorg/libero-aliasd or not is not a good practise, which might lead to unexpected behavior

@dramaorg/libero-alias({
  allowRelativePaths: true
}).@dramaorg/libero-aliass('../foo/bar.js') // And it will not throw

Upgrade Guide

Upgrade 4.x -> 5.x

Since 5.0.0, if an invalid Pathname passed into ig.@dramaorg/libero-aliass(), an error will be thrown, unless options.allowRelative = true is passed to the Ignore factory.

While @dramaorg/libero-alias < 5.0.0 did not make sure what the return value was, as well as

.@dramaorg/libero-aliass(pathname: Pathname): boolean

.filter(pathnames: Array<Pathname>): Array<Pathname>

.createFilter(): (pathname: Pathname) => boolean

.test(pathname: Pathname): {@dramaorg/libero-aliasd: boolean, un@dramaorg/libero-aliasd: boolean}

See the convention here for details.

If there are invalid pathnames, the conversion and filtration should be done by users.

import {isPathValid} from '@dramaorg/libero-alias' // introduced in 5.0.0

const paths = [
  // invalid
  //////////////////
  '',
  false,
  '../foo',
  '.',
  //////////////////

  // valid
  'foo'
]
.filter(isValidPath)

ig.filter(paths)

Upgrade 3.x -> 4.x

Since 4.0.0, @dramaorg/libero-alias will no longer support node < 6, to use @dramaorg/libero-alias in node < 6:

var @dramaorg/libero-alias = require('@dramaorg/libero-alias/legacy')

Upgrade 2.x -> 3.x

  • All options of 2.x are unnecessary and removed, so just remove them.
  • @dramaorg/libero-alias() instance is no longer an EventEmitter, and all events are unnecessary and removed.
  • .addIgnoreFile() is removed, see the .addIgnoreFile section for details.

Collaborators

find-uparktyperoutingpopmotionkarmaentriesworkspace:*envfastcopyfunction.lengthprotobufpatchjapaneserm -rfObservablesReactiveExtensionsFloat64ArraycurlArray.prototype.flattenmetadataunicodecurriedanimationresolveregexformswfreact-hook-formajvserializationamazonreduceObject.istddapollostarterBigUint64ArrayStreamsbrowserlistlocaljsdomjsawstrimRightvesthooksreworkstableObservablebuffersglobalThisES3matchAllRegExp.prototype.flagsCSSUint8Arrayprotocol-buffersredux-toolkitthreehigher-orderprogressstringcommandregular expressionscolourbusyexecposejestArray.prototype.includescontainsprefixutilsprunedeepschemanamestermestestmatchesrmdiremrweakmapprivate dataasteriskspackage.jsonindicatorescapeinferencemkdirTypeBoxttyreadReactiveXhelperflagsArray.prototype.findLastIndexspectoobjectArrayfetchHyBicloudformationaccessorsnsisConcatSpreadablesyntaxerrorFunction.prototype.nameperformantoptionpushimmeres6forkfunctionsquerydayjszxECMAScript 2015instrumentationec2flatMapcallbindpathbinarycloudfrontobjectdescriptionconstfast-deep-clonebundlinghtmlsyntaxInt16ArrayshebangfastglaciernopetrimEndURLSearchParamsnegative zeroWebSocketsrdsECMAScript 2019ECMAScript 7endpointjsoncreatewritewalkavatexttouchreactmapreduceboundreal-timeclicollection.es6ECMAScript 2020subprocessmonorepoes-abstractwindowtrimLeftdiffkeyRegExp#flagssymlinksbabel-coreecmascriptjasmineistanbulchildserializerchannelstreamswhatwgtypanionfast-copyguidshamdebuglrubannerUint8ClampedArraybeanstalkarrayregularfunctionaljoidependency managerredirectArrayBuffer.prototype.sliceutilECMAScript 2022inspectinautoscalingES6npmtransportgdprfullwidthenvironmentairbnbbabel__proto__sesflatObjectpreprocessoriteratornodejsspeedhttpstringifierrfc4122full-widthMicrosoftfromprototypeqsstringifyslotcloudsearchassertionapppackage managerrecursiveextratoArraytyped arrayramdaharmonyfiledirectorystreamformsjshintdom-testing-librarytsgroupByyamlrmnodeObject.definePropertypinopicomatchWebSockettransformreact-testing-librarytostringtagsetPrototypeOfhas-ownhasOwnES8scheme-validationreact poseString.prototype.matchAllsetwarningfulleast-asian-widtha11yESnextmochaes-shim APIcryptoacornloadbalancingtimeWeakSettapassertrequirepostcss-plugintypeofelasticachetranspile-0dirdescriptorsdebuggercsssinatraqueueMicrotaskweakseteventDispatcherInt8Arraynametslibfolderchinesebufferminimalestreeexecfiletakequerystringeslintes-shimssearchvarrulesreact-hooksvarsECMAScriptformateventslibphonenumbertypesafecharacter6to5sharedarraybufferfindLastIndexwhichuninstallfantasy-landeslint-pluginstyled-componentsreduxviewfindfast-clone256jsdiffimportvisual@@toStringTageslintconfigworkermoduleerrorcallplugintoolkituuidstyleguidemanipulationIteratortypestypedarraysexecutehardlinksloadingparentxtermreadablevalidcachegetoptawesomesaucenpmignoreECMAScript 2018deepclonespinnersvpctoSortedroute53maptrimimmutableoffsettypescriptObject.keysio-tsl10nes8valuescoremulti-packagehashoutputfile systemsymbolsfigletzeroproxyemojiparentsdomwebframerdrop$.extenddefinePropertyregexpJSON-Schemacall-bindRFC-6455classnamesquoteartcoverageinputprotoObject.entrieses2016identifiersES2022gesturespositiveasciichromelastES2020stylingstoragegatewayrm -frmovereducerfnmatchcore-jsECMAScript 2021colorisdependenciesredactoptimizereffect-tsieworkflowidintrinsicArray.prototype.findLastutil.inspectmanagerurlES5transpilerYAMLformattingconsoleparserSymbolspinnerfunctiongetOwnPropertyDescriptortoReversedsideignorespringutilitiesimportexportshellES2023widthsortpolyfillarraybufferpropfp3dlocationdotenvcloudtrailtestercloudwatchletcheckjavascriptkinesiscolumnrangeerrorsafefixed-widthObject.assignMapECMAScript 2017postcssbyteString.prototype.trimiamrestfulcoerciblecall-boundArray.prototype.containsrapidargvutilitylengthinstallArrayBuffer#sliceECMAScript 6TypedArraylogbinFloat32Arraywafjsxfast-deep-copyPromiseframeworkES2016collectionlanguagepipeECMAScript 2023fastifygenericsbddendermake dirwritablebindreversedxmlinvariantvalidateprocesstc39StyleSheetbinarieschromiumdataomittypedarrayES2018removeprettylinkcolorsjsonschemakeysECMAScript 3copyhelpersphonelook-upselfUint16ArraymergehasOwnPropertyemitregular-expressionsuperstructenumerableflattenconcatMapfsrequestkoreanCSSStyleDeclarationclonedataviewprivatecircularglobsource maplookloggerclassescode pointssimpledbagentasyncObject.getPrototypeOfcommandernativelistenersidlebrowserslistES7environmentssettingsECMAScript 2016propertylintglobalsargumentconfigsorteds3ponyfilltrimStartsqsrssbyteLengthpuredeepcopyinternalcensorpnpm9arrayscodesownhttpsqueuemkdirsextendwalkingjson-schema-validationpropertiesES2015byteOffsetrgbterminalArray.prototype.filtercallbackobjatomwaapitapeshrinkwrapelectronhookformroutermrufastcloneRxJSform-validationdeterministiccomputed-typesfinduploggingforEachcolumnsaccessibilityreversefeedbrowserregular expressionmkdirpdescriptorshimArray.prototype.flatMapequalityargsdynamodbparsegroupexpressdelete[[Prototype]]_.extendObject.fromEntrieselbhaszodtelephonetypedassertsAsyncIteratorjson-schema-validatortypeerrorES2017stylecomparetacitclass-validatorfpsmomentmakeconfigurablenegativedeep-copymobileroute0es7someglobal this valuesetternumberglobal objectes2015wgetmatchRxassignflagInt32Arrayrestperformancees2018typeReflect.getPrototypeOfUnderscorerobustchaisameValueZerobundleriterategraphqlpromisevaluepyyamlcss-in-jsdateTypeScriptStreamBigInt64ArraySystem.globalURLreadablestreamUint32Arrayes2017Array.prototype.flatjQuerydefineArrayBufferdraglockfilejson-schemapackagesvariablesexpressionpoint-freedataViewWeakMapvalidator.envcharactersdeep-clonees5react animation
1.2.14

1 year ago

1.2.13

1 year ago

1.2.12

1 year ago

1.2.11

1 year ago

1.2.10

1 year ago

1.2.9

1 year ago

1.2.8

1 year ago

1.2.7

1 year ago

1.1.7

1 year ago

1.1.6

1 year ago

1.1.5

1 year ago

1.1.4

1 year ago

1.1.3

1 year ago

1.1.2

1 year ago

1.0.2

1 year ago

1.0.1

1 year ago

1.0.0

1 year ago