This commit is contained in:
Code 2025-01-29 17:40:56 +01:00
parent 1db73dcf2b
commit e661d1c779
344 changed files with 50321 additions and 55 deletions

39
.github/workflows/release.yml vendored Normal file
View File

@ -0,0 +1,39 @@
name: Release
on:
push:
branches:
- main
concurrency: ${{ github.workflow }}-${{ github.ref }}
jobs:
release:
name: Release
runs-on: ubuntu-latest
steps:
- name: Checkout Repo
uses: actions/checkout@v4
- name: Setup Node.js 20.x
uses: actions/setup-node@v4
with:
node-version: 20
- name: Install Dependencies
run: yarn
- name: Create Release Pull Request or Publish to npm
id: changesets
uses: changesets/action@v1
with:
# This expects you to have a script called release which does a build for your packages and calls changeset publish
publish: yarn release
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
- name: Send a Slack notification if a publish happens
if: steps.changesets.outputs.published == 'true'
# You can do something when a publish happens.
run: my-slack-bot send-notification --message "A new version of ${GITHUB_REPOSITORY} was published!"

12
.gitignore vendored
View File

@ -1,4 +1,10 @@
/node_modules
/coverage
*.log
.DS_Store
node_modules
.turbo
*.log
.next
*.local
.env
.cache
storybook-static/
.kbot

2
.npmrc Normal file
View File

@ -0,0 +1,2 @@
auto-install-peers = true
public-hoist-pattern[]=*storybook*

7
.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,7 @@
{
"eslint.workingDirectories": [
{
"mode": "auto"
}
]
}

View File

@ -1,9 +0,0 @@
Copyright (c) <year> <owner> All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

193
README.md
View File

@ -1,3 +1,192 @@
# osr-package-template
# Turborepo Design System Starter
Package basics
This guide explains how to use a React design system starter powered by:
- 🏎 [Turborepo](https://turbo.build/repo) — High-performance build system for Monorepos
- 🚀 [React](https://reactjs.org/) — JavaScript library for user interfaces
- 🛠 [Tsup](https://github.com/egoist/tsup) — TypeScript bundler powered by esbuild
- 📖 [Storybook](https://storybook.js.org/) — UI component environment powered by Vite
As well as a few others tools preconfigured:
- [TypeScript](https://www.typescriptlang.org/) for static type checking
- [ESLint](https://eslint.org/) for code linting
- [Prettier](https://prettier.io) for code formatting
- [Changesets](https://github.com/changesets/changesets) for managing versioning and changelogs
- [GitHub Actions](https://github.com/changesets/action) for fully automated package publishing
## Using this example
Run the following command:
```sh
npx create-turbo@latest -e design-system
```
### Useful Commands
- `pnpm build` - Build all packages, including the Storybook site
- `pnpm dev` - Run all packages locally and preview with Storybook
- `pnpm lint` - Lint all packages
- `pnpm changeset` - Generate a changeset
- `pnpm clean` - Clean up all `node_modules` and `dist` folders (runs each package's clean script)
## Turborepo
[Turborepo](https://turbo.build/repo) is a high-performance build system for JavaScript and TypeScript codebases. It was designed after the workflows used by massive software engineering organizations to ship code at scale. Turborepo abstracts the complex configuration needed for monorepos and provides fast, incremental builds with zero-configuration remote caching.
Using Turborepo simplifies managing your design system monorepo, as you can have a single lint, build, test, and release process for all packages. [Learn more](https://vercel.com/blog/monorepos-are-changing-how-teams-build-software) about how monorepos improve your development workflow.
## Apps & Packages
This Turborepo includes the following packages and applications:
- `apps/docs`: Component documentation site with Storybook
- `packages/ui`: Core React components
- `packages/utils`: Shared React utilities
- `packages/typescript-config`: Shared `tsconfig.json`s used throughout the Turborepo
- `packages/eslint-config`: ESLint preset
Each package and app is 100% [TypeScript](https://www.typescriptlang.org/). Workspaces enables us to "hoist" dependencies that are shared between packages to the root `package.json`. This means smaller `node_modules` folders and a better local dev experience. To install a dependency for the entire monorepo, use the `-w` workspaces flag with `pnpm add`.
This example sets up your `.gitignore` to exclude all generated files, other folders like `node_modules` used to store your dependencies.
### Compilation
To make the core library code work across all browsers, we need to compile the raw TypeScript and React code to plain JavaScript. We can accomplish this with `tsup`, which uses `esbuild` to greatly improve performance.
Running `pnpm build` from the root of the Turborepo will run the `build` command defined in each package's `package.json` file. Turborepo runs each `build` in parallel and caches & hashes the output to speed up future builds.
For `acme-core`, the `build` command is the following:
```bash
tsup src/index.tsx --format esm,cjs --dts --external react
```
`tsup` compiles `src/index.tsx`, which exports all of the components in the design system, into both ES Modules and CommonJS formats as well as their TypeScript types. The `package.json` for `acme-core` then instructs the consumer to select the correct format:
```json:acme-core/package.json
{
"name": "@acme/core",
"version": "0.0.0",
"main": "./dist/index.js",
"module": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"sideEffects": false,
}
```
Run `pnpm build` to confirm compilation is working correctly. You should see a folder `acme-core/dist` which contains the compiled output.
```bash
acme-core
└── dist
├── index.d.ts <-- Types
├── index.js <-- CommonJS version
└── index.mjs <-- ES Modules version
```
## Components
Each file inside of `acme-core/src` is a component inside our design system. For example:
```tsx:acme-core/src/Button.tsx
import * as React from 'react';
export interface ButtonProps {
children: React.ReactNode;
}
export function Button(props: ButtonProps) {
return <button>{props.children}</button>;
}
Button.displayName = 'Button';
```
When adding a new file, ensure the component is also exported from the entry `index.tsx` file:
```tsx:acme-core/src/index.tsx
import * as React from "react";
export { Button, type ButtonProps } from "./Button";
// Add new component exports here
```
## Storybook
Storybook provides us with an interactive UI playground for our components. This allows us to preview our components in the browser and instantly see changes when developing locally. This example preconfigures Storybook to:
- Use Vite to bundle stories instantly (in milliseconds)
- Automatically find any stories inside the `stories/` folder
- Support using module path aliases like `@acme-core` for imports
- Write MDX for component documentation pages
For example, here's the included Story for our `Button` component:
```js:apps/docs/stories/button.stories.mdx
import { Button } from '@acme-core/src';
import { Meta, Story, Preview, Props } from '@storybook/addon-docs/blocks';
<Meta title="Components/Button" component={Button} />
# Button
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec euismod, nisl eget consectetur tempor, nisl nunc egestas nisi, euismod aliquam nisl nunc euismod.
## Props
<Props of={Box} />
## Examples
<Preview>
<Story name="Default">
<Button>Hello</Button>
</Story>
</Preview>
```
This example includes a few helpful Storybook scripts:
- `pnpm dev`: Starts Storybook in dev mode with hot reloading at `localhost:6006`
- `pnpm build`: Builds the Storybook UI and generates the static HTML files
- `pnpm preview-storybook`: Starts a local server to view the generated Storybook UI
## Versioning & Publishing Packages
This example uses [Changesets](https://github.com/changesets/changesets) to manage versions, create changelogs, and publish to npm. It's preconfigured so you can start publishing packages immediately.
You'll need to create an `NPM_TOKEN` and `GITHUB_TOKEN` and add it to your GitHub repository settings to enable access to npm. It's also worth installing the [Changesets bot](https://github.com/apps/changeset-bot) on your repository.
### Generating the Changelog
To generate your changelog, run `pnpm changeset` locally:
1. **Which packages would you like to include?** This shows which packages and changed and which have remained the same. By default, no packages are included. Press `space` to select the packages you want to include in the `changeset`.
1. **Which packages should have a major bump?** Press `space` to select the packages you want to bump versions for.
1. If doing the first major version, confirm you want to release.
1. Write a summary for the changes.
1. Confirm the changeset looks as expected.
1. A new Markdown file will be created in the `changeset` folder with the summary and a list of the packages included.
### Releasing
When you push your code to GitHub, the [GitHub Action](https://github.com/changesets/action) will run the `release` script defined in the root `package.json`:
```bash
turbo run build --filter=docs^... && changeset publish
```
Turborepo runs the `build` script for all publishable packages (excluding docs) and publishes the packages to npm. By default, this example includes `acme` as the npm organization. To change this, do the following:
- Rename folders in `packages/*` to replace `acme` with your desired scope
- Search and replace `acme` with your desired scope
- Re-run `pnpm install`
To publish packages to a private npm organization scope, **remove** the following from each of the `package.json`'s
```diff
- "publishConfig": {
- "access": "public"
- },
```

92
eslint.config.js Normal file
View File

@ -0,0 +1,92 @@
import tseslint from 'typescript-eslint';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
// plugins
import regexpEslint from 'eslint-plugin-regexp';
const typescriptEslint = tseslint.plugin;
// parsers
const typescriptParser = tseslint.parser;
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
/** @type {import('eslint').Linter.Config[]} */
export default [
{ files: ["src/*.{js,mjs,cjs,ts}"] },
// { languageOptions: { globals: globals.browser } },
...tseslint.configs.recommendedTypeChecked,
...tseslint.configs.stylisticTypeChecked,
regexpEslint.configs['flat/recommended'],
{
languageOptions: {
parser: typescriptParser,
parserOptions: {
project: ['./packages/*/tsconfig.json', './tsconfig.eslint.json'],
tsconfigRootDir: __dirname,
},
},
plugins: {
'@typescript-eslint': typescriptEslint,
regexp: regexpEslint,
},
rules: {
// These off/configured-differently-by-default rules fit well for us
'@typescript-eslint/switch-exhaustiveness-check': 'error',
'@typescript-eslint/no-shadow': 'off',
'no-console': 'off',
'@typescript-eslint/no-unsafe-enum-comparison': 'off',
'@typescript-eslint/no-empty-object-type': 'off',
// Todo: do we want these?
'no-var': 'off',
'regexp/prefer-regexp-exec': 'off',
'@typescript-eslint/no-duplicate-enum-values': 'off',
'@typescript-eslint/no-unsafe-function-type': 'off',
'@typescript-eslint/prefer-for-of': 'off',
'@typescript-eslint/no-unused-vars': 'off',
'@typescript-eslint/array-type': 'off',
'@typescript-eslint/ban-ts-comment': 'off',
'@typescript-eslint/class-literal-property-style': 'off',
'@typescript-eslint/consistent-indexed-object-style': 'off',
'@typescript-eslint/consistent-type-definitions': 'off',
'@typescript-eslint/dot-notation': 'off',
'@typescript-eslint/no-base-to-string': 'off',
'@typescript-eslint/no-empty-function': 'off',
'@typescript-eslint/no-floating-promises': 'off',
'@typescript-eslint/no-misused-promises': 'off',
'@typescript-eslint/no-redundant-type-constituents': 'off',
'@typescript-eslint/no-this-alias': 'off',
'@typescript-eslint/no-unsafe-argument': 'off',
'@typescript-eslint/no-unsafe-assignment': 'off',
'@typescript-eslint/no-unsafe-call': 'off',
'@typescript-eslint/no-unsafe-member-access': 'off',
'@typescript-eslint/no-unused-expressions': 'off',
'@typescript-eslint/only-throw-error': 'off',
'@typescript-eslint/no-unsafe-return': 'off',
'@typescript-eslint/no-unnecessary-type-assertion': 'off',
'@typescript-eslint/prefer-nullish-coalescing': 'off',
'@typescript-eslint/prefer-optional-chain': 'off',
'@typescript-eslint/prefer-promise-reject-errors': 'off',
'@typescript-eslint/prefer-string-starts-ends-with': 'off',
'@typescript-eslint/require-await': 'off',
'@typescript-eslint/restrict-plus-operands': 'off',
'@typescript-eslint/restrict-template-expressions': 'off',
'@typescript-eslint/sort-type-constituents': 'off',
'@typescript-eslint/unbound-method': 'off',
'@typescript-eslint/no-explicit-any': 'off',
// Used by Biome
'@typescript-eslint/consistent-type-imports': 'off',
// These rules enabled by the preset configs don't work well for us
'@typescript-eslint/await-thenable': 'off',
'prefer-const': 'off',
// In some cases, using explicit letter-casing is more performant than the `i` flag
'regexp/use-ignore-case': 'off',
'regexp/prefer-regexp-exec': 'warn',
'regexp/prefer-regexp-test': 'warn',
'no-control-regex': 'off'
}
}
]

View File

@ -1,45 +1,19 @@
{
"name": "@plastichub/template",
"description": "",
"version": "0.3.1",
"main": "main.js",
"typings": "index.d.ts",
"publishConfig": {
"access": "public"
},
"bin": {
"osr-bin": "main.js"
},
"dependencies": {
"@types/node": "^14.17.5",
"@types/yargs": "^17.0.2",
"chalk": "^2.4.1",
"convert-units": "^2.3.4",
"env-var": "^7.0.1",
"typescript": "^4.3.5",
"yargs": "^14.2.3",
"yargs-parser": "^15.0.3"
},
"private": true,
"scripts": {
"test": "tsc; mocha --full-trace mocha \"spec/**/*.spec.js\"",
"test-with-coverage": "istanbul cover node_modules/.bin/_mocha -- 'spec/**/*.spec.js'",
"lint": "tslint --project=./tsconfig.json",
"build": "tsc -p .",
"dev": "tsc -p . --declaration -w",
"typings": "tsc --declaration",
"docs": "npx typedoc src/index.ts",
"dev-test-watch": "mocha-typescript-watch"
"build": "turbo run build",
"dev": "turbo run dev",
"lint": "turbo run lint",
"clean": "turbo run clean && rm -rf node_modules",
"format": "prettier --write \"**/*.{ts,tsx,md}\"",
"changeset": "changeset",
"version-packages": "changeset version",
"release": "turbo run build --filter=docs^... && changeset publish"
},
"homepage": "https://git.osr-plastic.org/plastichub/lib-content",
"repository": {
"type": "git",
"url": "https://git.osr-plastic.org/plastichub/lib-content.git"
"devDependencies": {
"prettier": "^3.2.5",
"turbo": "^2.3.3"
},
"engines": {
"node": ">= 14.0.0"
},
"license": "BSD-3-Clause",
"keywords": [
"typescript"
]
"packageManager": "pnpm@8.15.6",
"name": "design-system"
}

12
packages/fs/.editorconfig Normal file
View File

@ -0,0 +1,12 @@
# http://editorconfig.org
root = true
[*]
indent_style = tab
indent_size = 4
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.md]
trim_trailing_whitespace = false

4
packages/fs/.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
/node_modules
/coverage
*.log
.DS_Store

View File

@ -1,4 +1,5 @@
./docs
./scripts
./tests
./incoming
./spec
./benchmark

10
packages/fs/.travis.yml Normal file
View File

@ -0,0 +1,10 @@
language: node_js
node_js:
- "9"
script:
- npm run test
after_success:
- ./node_modules/.bin/codecov

24
packages/fs/.vscode/launch.json vendored Normal file
View File

@ -0,0 +1,24 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Find",
"skipFiles": [
"<node_internals>/**"
],
"args": [
"find"
],
"program": "${workspaceFolder}\\main.js",
"preLaunchTask": "tsc: build - tsconfig.json",
"outFiles": [
"${workspaceFolder}/./**/*.js"
]
}
]
}

5
packages/fs/.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,5 @@
{
"cSpell.words": [
"throttel"
]
}

103
packages/fs/CHANGELOG.md Normal file
View File

@ -0,0 +1,103 @@
# 0.12.1 (2017-02-24)
- Typescript port complete
- all tests passing
# 0.11.0 (2017-02-09)
- Added input validation for the whole API
- **(breaking change)** Removed already deprecated option `buf` for `read()` method
# 0.10.5 (2016-12-07)
- Fixed `find()` bug when `directories` is set to `true` and only negation glob is used.
# 0.10.4 (2016-12-06)
- Fixed matcher edge cases, improved matcher tests (affects `find()` and `copy()` methods).
# 0.10.3 (2016-11-23)
- Fixed directory tree traversal bug which was causing problems for `findAsync()` and `copyAsync()`.
# 0.10.2 (2016-11-08)
- Fixed `console.log(jetpack)` for node v6.6.0 or newer.
# 0.10.1 (2016-11-01)
- Bugfixed case when `copyAsync()` was leaving open read stream if write stream errored.
- Tests ported from jasmine to mocha.
# 0.10.0 (2016-10-17)
- `copyAsync()` uses only streams (much more memory efficient).
- `find()` supports `recursive` option.
# 0.9.2 (2016-06-27)
- Updated third party dependencies to quell minimatch intallation warnings.
# 0.9.1 (2016-05-21)
- Bug-fixed `jetpack.read('nonexistent_file', 'json')`.
# 0.9.0 (2016-05-10)
- **(breaking change)** `read()`, `list()`, `inspect()` and `inspectTree()` returns `undefined` instead of `null` if path doesn't exist.
- More sane edge cases for `dir()`, `file()` and `list()`.
# 0.8.0 (2016-04-09)
- **(breaking change)** `find()` now distinguishes between files and directories and by default searches only for files (previously searched for both).
- **(breaking change)** `find()` no longer can be configured with `returnAs` parameter and returns always relative paths (previously returned absolute).
- **(breaking change)** `list()` no longer accepts `useInspect` as a parameter. To achieve old behaviour use `jetpack.list()` with `Array.map()`.
- **(deprecation)** Don't do `jetpack.read('sth', 'buf')`, do `jetpack.read('sth', 'buffer')` instead.
- `remove()`, `list()` and `find()` now can be called without provided `path`, and defaults to CWD in that case.
# 0.7.3 (2016-03-21)
- Bugfixed `copy()` with symlink overwrite
# 0.7.2 (2016-03-09)
- Fixed .dotfiles copying
# 0.7.1 (2015-12-17)
- Updated third party dependencies.
# 0.7.0 (2015-07-20)
- **(breaking change)** `matching` option in `copy()` and `find()` resolves glob patterns to the folder you want copy or find stuff in (previously CWD was used).
# 0.6.5 (2015-06-19)
- `exists()` can handle ENOTDIR error.
# 0.6.3 and 0.6.4 (2015-04-18)
- Added support for symbolic links.
# 0.6.2 (2015-04-07)
- Option `matching` in `copy()` and `find()` now accepts patterns anchored to CWD.
# 0.6.1 (2015-04-03)
- Option `matching` in `copy()` and `find()` now accepts negation patterns (e.g. `!some/file.txt`).
# 0.6.0 (2015-03-30)
- Lots of code refactoring
- **(breaking change)** `dir()` no longer has `exists` option.
- **(breaking change)** `file()` no longer has `exists` and `empty` options.
- **(breaking change)** `safe` option for `write()` renamed to `atomic` (and uses new algorithm under the hood).
- **(breaking change)** `safe` option for `read()` dropped (`atomic` while writing is enough).
- **(breaking change)** In `copy()` options `only` and `allBut` have been replaced by option `matching`.
- **(breaking change)** In `remove()` options `only` and `allBut` have been dropped (to do the same use `find()`, and then remove).
- **(breaking change)** Default jsonIndent changed form 0 to 2.
- `find()` method added.
- More telling errors when `read()` failed while parsing JSON.
# 0.5.3 (2015-01-06)
- `inspect()` can return file access/modify/change time and mode.
# 0.5.2 (2014-09-21)
- `inspect()` checksum of empty file is now `null`.
# 0.5.1 (2014-09-21)
- `cwd()` accepts many arguments as path parts.
# 0.5.0 (2014-08-31)
- **(breaking change)** Method `tree()` renamed to `inspectTree()`.
- **(breaking change)** Parameters passed to `list()` has changed.
- Methods `inspect()` and `inspectTree()` can calculate md5 and sha1 checksums.
- Added aliases to `fs.createReadStream()` and `fs.createWriteStream()`.
# 0.4.1 (2014-07-16)
- `copy()` now copies also file permissions on unix systems.
- `append()` can specify file mode if file doesn't exist.
- Can indent saved JSON data.
# 0.4.0 (2014-07-14)
- Changelog starts here.

82
packages/fs/EXAMPLES.md Normal file
View File

@ -0,0 +1,82 @@
# Cool things about fs-jetpack in examples
**Note:** All examples here are synchronous for simplicity. You can easily make them asynchronous just by adding 'Async' to method names and expecting promise to be returned instead of ready value.
## Every jetpack instance has its internal CWD
You can create many jetpack objects with different internal working directories (which are independent of `process.cwd()`) and work on directories in a little more object-oriented manner.
```js
var src = jetpack.cwd('path/to/source');
var dest = jetpack.cwd('path/to/destination');
src.copy('foo.txt', dest.path('bar.txt'));
```
## JSON is a first class citizen
You can write JavaScript object directly to disk and it will be transformed to JSON automatically.
```js
var obj = { greet: "Hello World!" };
jetpack.write('file.json', obj);
```
Then you can get your object back just by telling read method that it's a JSON.
```js
var obj = jetpack.read('file.json', 'json');
```
## Jetpack throws errors at you as the last resort
Everyone who did something with files for sure seen (and probably hates) *"ENOENT, no such file or directory"* error. Jetpack tries to recover from that error if possible.
1. For write/creation operations, if any of parent directories doesn't exist jetpack will just create lacking directories.
2. For read/inspect operations, if file or directory doesn't exist `undefined` is returned instead of throwing.
## Jetpack is great for build scripts
```js
var src = jetpack.cwd('path/to/source');
var dest = jetpack.dir('path/to/destination', { empty: true });
src.copy('.', dest.path(), {
matching: ['./vendor/**', '*.html', '*.png', '*.jpg']
});
var config = src.read('config.json', 'json');
config.env = 'production';
dest.write('config.json', config);
```
## All methods play nicely with each other
Let's say you want to create folder structure:
```
.
|- greets
|- greet.txt
|- greet.json
|- greets-i18n
|- polish.txt
```
Peace of cake with jetpack!
```js
jetpack
.dir('greets')
.file('greet.txt', { content: 'Hello world!' })
.file('greet.json', { content: { greet: 'Hello world!' } })
.cwd('..')
.dir('greets-i18n')
.file('polish.txt', { content: 'Witaj świecie!' });
```
## Find and delete all `.tmp` files inside `my-dir`
```js
jetpack.find('my-dir', {
matching: '*.tmp'
})
.forEach(jetpack.remove);
```
## Check if two files have the same content
```js
var file1 = jetpack.inspect('file1', { checksum: 'md5' });
var file2 = jetpack.inspect('file2', { checksum: 'md5' });
var areTheSame = (file1.md5 === file2.md5);
```
## More secure writes to disk
For essential data you might consider "atomic write" feature. To read more about "why" and "how" please see: [Transactionally writing files in Node.js](http://stackoverflow.com/questions/17047994/transactionally-writing-files-in-node-js) Jetpack implements this simple trick and makes it available as an option.
```js
jetpack.write('important_config.json', { atomic: true });
```

28
packages/fs/LICENSE Normal file
View File

@ -0,0 +1,28 @@
The "New" BSD License
*********************
Copyright (c) 2015 - 2016, xblox
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the xblox nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

20
packages/fs/README.md Normal file
View File

@ -0,0 +1,20 @@
# Advanced filesystem implementation in Typescript
- [ ] Correct totals
- [ ] support streams
- [ ] Switch to fast glob
- [x] Remap nodes for cp and mv
- [x] zero conf
- [ ] update unit tests
- [-] common CLI commands for global: each, concat, cat (with plugins)
- [-] rimraf rename plugin, part of `each <glob>`
- [ ] node type incorrect for invalid file/folder names
- [-] update to latest fs-jetpack
- [ ] WSAENAMETOOLONG
- [ ] diff
- [ ] images
- [ ] defaults : path limit, ARS, busy
## References
- [https://github.com/alessioalex/get-folder-size](https://github.com/alessioalex/get-folder-size)

10
packages/fs/append.d.ts vendored Normal file
View File

@ -0,0 +1,10 @@
/// <reference types="node" />
/// <reference types="node" />
export interface Options {
mode: string;
encoding?: string;
flag?: string;
}
export declare const validateInput: (methodName: string, path: string, data: any, options?: Options) => void;
export declare const sync: (path: string, data: any, options: Options) => void;
export declare const async: (path: string, data: string | Buffer | Object, options?: Options) => Promise<null>;

57
packages/fs/append.js Normal file
View File

@ -0,0 +1,57 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.async = exports.sync = exports.validateInput = void 0;
const fs = require("fs");
const Q = require('q');
const write_1 = require("./write");
const validate_1 = require("./utils/validate");
const validateInput = (methodName, path, data, options) => {
const methodSignature = methodName + '(path, data, [options])';
(0, validate_1.validateArgument)(methodSignature, 'path', path, ['string']);
(0, validate_1.validateArgument)(methodSignature, 'data', data, ['string', 'buffer']);
(0, validate_1.validateOptions)(methodSignature, 'options', options, {
mode: ['string', 'number']
});
};
exports.validateInput = validateInput;
// ---------------------------------------------------------
// SYNC
// ---------------------------------------------------------
const sync = (path, data, options) => {
try {
fs.appendFileSync(path, data, options ? { encoding: options.encoding, mode: options.mode } : {});
}
catch (err) {
if (err.code === 'ENOENT') {
// Parent directory doesn't exist, so just pass the task to `write`,
// which will create the folder and file.
(0, write_1.sync)(path, data, options);
}
else {
throw err;
}
}
};
exports.sync = sync;
// ---------------------------------------------------------
// ASYNC
// ---------------------------------------------------------
const promisedAppendFile = Q.denodeify(fs.appendFile);
const async = (path, data, options) => {
return new Promise((resolve, reject) => {
promisedAppendFile(path, data, options)
.then(resolve)
.catch((err) => {
if (err.code === 'ENOENT') {
// Parent directory doesn't exist, so just pass the task to `write`,
// which will create the folder and file.
(0, write_1.async)(path, data, options).then(resolve, reject);
}
else {
reject(err);
}
});
});
};
exports.async = async;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYXBwZW5kLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsic3JjL2FwcGVuZC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7QUFBQSx5QkFBeUI7QUFDekIsTUFBTSxDQUFDLEdBQUcsT0FBTyxDQUFDLEdBQUcsQ0FBQyxDQUFDO0FBQ3ZCLG1DQUFpRTtBQUNqRSwrQ0FBcUU7QUFPOUQsTUFBTSxhQUFhLEdBQUcsQ0FBQyxVQUFrQixFQUFFLElBQVksRUFBRSxJQUFTLEVBQUUsT0FBaUIsRUFBRSxFQUFFO0lBQzlGLE1BQU0sZUFBZSxHQUFHLFVBQVUsR0FBRyx5QkFBeUIsQ0FBQztJQUMvRCxJQUFBLDJCQUFnQixFQUFDLGVBQWUsRUFBRSxNQUFNLEVBQUUsSUFBSSxFQUFFLENBQUMsUUFBUSxDQUFDLENBQUMsQ0FBQztJQUM1RCxJQUFBLDJCQUFnQixFQUFDLGVBQWUsRUFBRSxNQUFNLEVBQUUsSUFBSSxFQUFFLENBQUMsUUFBUSxFQUFFLFFBQVEsQ0FBQyxDQUFDLENBQUM7SUFDdEUsSUFBQSwwQkFBZSxFQUFDLGVBQWUsRUFBRSxTQUFTLEVBQUUsT0FBTyxFQUFFO1FBQ25ELElBQUksRUFBRSxDQUFDLFFBQVEsRUFBRSxRQUFRLENBQUM7S0FDM0IsQ0FBQyxDQUFDO0FBQ0wsQ0FBQyxDQUFDO0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CAAC,IAAI,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;aACvD;iBAAM;gBACL,MAAM,CAAC,GAAG,CAAC,CAAC;aACb;QACH,CAAC,CAAC,CAAC;IACP,CAAC,CAAC,CAAC;AACL,CAAC,CAAC;AAdW,QAAA,KAAK,SAchB"}

25
packages/fs/appveyor.yml Normal file
View File

@ -0,0 +1,25 @@
# appveyor file
# http://www.appveyor.com/docs/appveyor-yml
version: "{build}"
environment:
matrix:
- nodejs_version: "8"
install:
- ps: Install-Product node $env:nodejs_version
- npm install
test_script:
# Output useful info for debugging.
- node --version
- npm --version
# run tests
- npm test
build: off
branches:
only:
- master

View File

@ -0,0 +1,96 @@
// Benchmark to make sure performance of copy is near 'native' bash command.
/* eslint no-console: 0 */
'use strict';
var Q = require('q');
var os = require('os');
var childProcess = require('child_process');
var promisedExec = Q.denodeify(childProcess.exec);
var benchUtils = require('./utils');
var jetpack = require('..');
var testDir = jetpack.dir(os.tmpdir() + '/jetpack-benchmark', { empty: true });
var toCopyDir = testDir.dir('to-copy');
var timer;
var jetpackTime;
var nativeTime;
var prepareFiles = function (testConfig) {
return new Q.Promise(function (resolve, reject) {
var count = 0;
var content = new Buffer(testConfig.size);
var makeOneFile = function () {
toCopyDir.fileAsync(count + '.txt', { content: content })
.then(function () {
count += 1;
if (count < testConfig.files) {
makeOneFile();
} else {
resolve();
}
}, reject);
};
console.log('Preparing ' + testConfig.files + ' test files (' +
benchUtils.humanFileSize(testConfig.size, true) + ' each)...');
makeOneFile();
});
};
var waitAWhile = function () {
return new Q.Promise(function (resolve) {
console.log('Waiting 10s to allow hardware buffers be emptied...');
setTimeout(resolve, 10000);
});
};
var test = function (testConfig) {
console.log('----------------------');
return prepareFiles(testConfig)
.then(waitAWhile)
.then(function () {
timer = benchUtils.startTimer('jetpack.copyAsync()');
return toCopyDir.copyAsync('.', testDir.path('copied-jetpack'));
})
.then(function () {
jetpackTime = timer();
return waitAWhile();
})
.then(function () {
timer = benchUtils.startTimer('Native cp -R');
return promisedExec('cp -R ' + toCopyDir.path() + ' ' + testDir.path('copied-native'));
})
.then(function () {
nativeTime = timer();
console.log('Jetpack is ' + (jetpackTime / nativeTime).toFixed(1) +
' times slower than native');
console.log('Cleaning up after test...');
return testDir.removeAsync();
})
.catch(function (err) {
console.log(err);
});
};
var testConfigs = [{
files: 10000,
size: 100
}, {
files: 1000,
size: 1000 * 100
}, {
files: 100,
size: 1000 * 1000 * 10
}];
var runNext = function () {
if (testConfigs.length > 0) {
test(testConfigs.pop()).then(runNext);
}
};
runNext();

View File

@ -0,0 +1,97 @@
/* eslint no-console:0 */
'use strct';
var os = require('os');
var childProcess = require('child_process');
var promisify = require('../lib/utils/promisify');
var jetpack = require('..');
var humanReadableFileSize = function (bytes, si) {
var units;
var u;
var b = bytes;
var thresh = si ? 1000 : 1024;
if (Math.abs(b) < thresh) {
return b + ' B';
}
units = si
? ['kB', 'MB', 'GB', 'TB']
: ['KiB', 'MiB', 'GiB', 'TiB'];
u = -1;
do {
b /= thresh;
++u;
} while (Math.abs(b) >= thresh && u < units.length - 1);
return b.toFixed(1) + ' ' + units[u];
};
var testDirPath = function () {
return os.tmpdir() + '/jetpack-benchmark';
};
var prepareJetpackTestDir = function () {
return jetpack.dir(testDirPath(), { empty: true });
};
var prepareFiles = function (jetpackDir, creationConfig) {
return new Promise(function (resolve, reject) {
var count = 0;
var content = new Buffer(creationConfig.size);
var makeOneFile = function () {
jetpackDir.fileAsync(count + '.txt', { content: content })
.then(function () {
count += 1;
if (count < creationConfig.files) {
makeOneFile();
} else {
resolve();
}
}, reject);
};
console.log('Preparing ' + creationConfig.files + ' test files (' +
humanReadableFileSize(creationConfig.size, true) + ' each)...');
makeOneFile();
});
};
var startTimer = function (startMessage) {
var start = Date.now();
process.stdout.write(startMessage + ' ... ');
return function stop() {
var time = Date.now() - start;
console.log(time + 'ms');
return time;
};
};
var waitAWhile = function () {
return new Promise(function (resolve) {
console.log('Waiting 5s to allow hardware buffers be emptied...');
setTimeout(resolve, 5000);
});
};
var promisedExec = promisify(childProcess.exec);
var showDifferenceInfo = function (jetpackTime, nativeTime) {
var perc = Math.round(jetpackTime / nativeTime * 100) - 100;
console.log('Jetpack is ' + perc + '% slower than native');
};
var cleanAfterTest = function () {
console.log('Cleaning up after test...');
return jetpack.removeAsync(testDirPath());
};
module.exports = {
prepareJetpackTestDir: prepareJetpackTestDir,
prepareFiles: prepareFiles,
startTimer: startTimer,
waitAWhile: waitAWhile,
exec: promisedExec,
showDifferenceInfo: showDifferenceInfo,
cleanAfterTest: cleanAfterTest
};

9
packages/fs/build/append.d.ts vendored Normal file
View File

@ -0,0 +1,9 @@
/// <reference types="node" />
export interface Options {
mode: string;
encoding?: string;
flag?: string;
}
export declare const validateInput: (methodName: string, path: string, data: any, options?: Options) => void;
export declare const sync: (path: string, data: any, options: Options) => void;
export declare const async: (path: string, data: string | Object | Buffer, options?: Options) => Promise<null>;

View File

@ -0,0 +1,53 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const fs = require("fs");
const Q = require('q');
const write_1 = require("./write");
const validate_1 = require("./utils/validate");
exports.validateInput = (methodName, path, data, options) => {
const methodSignature = methodName + '(path, data, [options])';
validate_1.validateArgument(methodSignature, 'path', path, ['string']);
validate_1.validateArgument(methodSignature, 'data', data, ['string', 'buffer']);
validate_1.validateOptions(methodSignature, 'options', options, {
mode: ['string', 'number']
});
};
// ---------------------------------------------------------
// SYNC
// ---------------------------------------------------------
exports.sync = (path, data, options) => {
try {
fs.appendFileSync(path, data, options ? { encoding: options.encoding, mode: options.mode } : {});
}
catch (err) {
if (err.code === 'ENOENT') {
// Parent directory doesn't exist, so just pass the task to `write`,
// which will create the folder and file.
write_1.sync(path, data, options);
}
else {
throw err;
}
}
};
// ---------------------------------------------------------
// ASYNC
// ---------------------------------------------------------
const promisedAppendFile = Q.denodeify(fs.appendFile);
exports.async = (path, data, options) => {
return new Promise((resolve, reject) => {
promisedAppendFile(path, data, options)
.then(resolve)
.catch((err) => {
if (err.code === 'ENOENT') {
// Parent directory doesn't exist, so just pass the task to `write`,
// which will create the folder and file.
write_1.async(path, data, options).then(resolve, reject);
}
else {
reject(err);
}
});
});
};
//# sourceMappingURL=append.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"append.js","sourceRoot":"","sources":["../src/append.ts"],"names":[],"mappings":";;AAAA,yBAAyB;AACzB,MAAM,CAAC,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC;AACvB,mCAAiE;AACjE,+CAAqE;AAOxD,QAAA,aAAa,GAAG,CAAC,UAAkB,EAAE,IAAY,EAAE,IAAS,EAAE,OAAiB,EAAE,EAAE;IAC9F,MAAM,eAAe,GAAG,UAAU,GAAG,yBAAyB,CAAC;IAC/D,2BAAgB,CAAC,eAAe,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,QAAQ,CAAC,CAAC,CAAC;IAC5D,2BAAgB,CAAC,eAAe,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC,CAAC;IACtE,0BAAe,CAAC,eAAe,EAAE,SAAS,EAAE,OAAO,EAAE;QACnD,IAAI,EAAE,CAAC,QAAQ,EAAE,QAAQ,CAAC;KAC3B,CAAC,CAAC;AACL,CAAC,CAAC;AACF,4DAA4D;AAC5D,OAAO;AACP,4DAA4D;AAC/C,QAAA,IAAI,GAAG,CAAC,IAAY,EAAE,IAAS,EAAE,OAAgB,EAAQ,EAAE;IACtE,IAAI,CAAC;QACH,EAAE,CAAC,cAAc,CAAC,IAAI,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,OAAO,CAAC,QAAQ,EAAE,IAAI,EAAE,OAAO,CAAC,IAAc,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;IAC7G,CAAC;IAAC,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;QACb,EAAE,CAAC,CAAC,GAAG,CAAC,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC;YAC1B,oEAAoE;YACpE,yCAAyC;YACzC,YAAS,CAAC,IAAI,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC;QACjC,CAAC;QAAC,IAAI,CAAC,CAAC;YACN,MAAM,GAAG,CAAC;QACZ,CAAC;IACH,CAAC;AACH,CAAC,CAAC;AAEF,4DAA4D;AAC5D,QAAQ;AACR,4DAA4D;AAC5D,MAAM,kBAAkB,GAAG,CAAC,CAAC,SAAS,CAAC,EAAE,CAAC,UAAU,CAAC,CAAC;AACzC,QAAA,KAAK,GAAG,CAAC,IAAY,EAAE,IAA8B,EAAE,OAAiB,EAAiB,EAAE;IACtG,MAAM,CAAC,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACrC,kBAAkB,CAAC,IAAI,EAAE,IAAI,EAAE,OAAO,CAAC;aACpC,IAAI,CAAC,OAAO,CAAC;aACb,KAAK,CAAC,CAAC,GAAQ,EAAE,EAAE;YAClB,EAAE,CAAC,CAAC,GAAG,CAAC,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC;gBAC1B,oEAAoE;gBACpE,yCAAyC;gBACzC,aAAU,CAAC,IAAI,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;YACxD,CAAC;YAAC,IAAI,CAAC,CAAC;gBACN,MAAM,CAAC,GAAG,CAAC,CAAC;YACd,CAAC;QACH,CAAC,CAAC,CAAC;IACP,CAAC,CAAC,CAAC;AACL,CAAC,CAAC"}

14
packages/fs/build/copy.d.ts vendored Normal file
View File

@ -0,0 +1,14 @@
import { ICopyOptions, EResolveMode, TCopyResult } from './interfaces';
export declare function validateInput(methodName: string, from: string, to: string, options?: ICopyOptions): void;
export declare function sync(from: string, to: string, options?: ICopyOptions): void;
export declare function copySymlinkAsync(from: string, to: string): Promise<{}>;
export declare function resolveConflict(from: string, to: string, options: ICopyOptions, resolveMode: EResolveMode): boolean;
/**
* Final async copy function.
* @export
* @param {string} from
* @param {string} to
* @param {ICopyOptions} [options]
* @returns
*/
export declare function async(from: string, to: string, options?: ICopyOptions): Promise<TCopyResult>;

624
packages/fs/build/copy.js Normal file
View File

@ -0,0 +1,624 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const pathUtil = require("path");
const fs = require("fs");
const fs_1 = require("fs");
const mkdirp = require("mkdirp");
const exists_1 = require("./exists");
const matcher_1 = require("./utils/matcher");
const mode_1 = require("./utils/mode");
const tree_walker_1 = require("./utils/tree_walker");
const validate_1 = require("./utils/validate");
const write_1 = require("./write");
const errors_1 = require("./errors");
const interfaces_1 = require("./interfaces");
const inspect_1 = require("./inspect");
const remove_1 = require("./remove");
const promisify_1 = require("./promisify");
const iterator_1 = require("./iterator");
const promisedSymlink = promisify_1.promisify(fs.symlink);
const promisedReadlink = promisify_1.promisify(fs.readlink);
const promisedUnlink = promisify_1.promisify(fs.unlink);
const promisedMkdirp = promisify_1.promisify(mkdirp);
const progress = require('progress-stream');
const throttle = require('throttle');
const CPROGRESS_THRESHOLD = 1048576 * 5; // minimum file size threshold to use write progress = 5MB
function validateInput(methodName, from, to, options) {
const methodSignature = methodName + '(from, to, [options])';
validate_1.validateArgument(methodSignature, 'from', from, ['string']);
validate_1.validateArgument(methodSignature, 'to', to, ['string']);
validate_1.validateOptions(methodSignature, 'options', options, {
overwrite: ['boolean'],
matching: ['string', 'array of string'],
progress: ['function'],
writeProgress: ['function'],
conflictCallback: ['function'],
conflictSettings: ['object'],
throttel: ['number'],
debug: ['boolean'],
flags: ['number']
});
}
exports.validateInput = validateInput;
const parseOptions = (options, from) => {
const opts = options || {};
const parsedOptions = {};
parsedOptions.overwrite = opts.overwrite;
parsedOptions.progress = opts.progress;
parsedOptions.writeProgress = opts.writeProgress;
parsedOptions.conflictCallback = opts.conflictCallback;
parsedOptions.conflictSettings = opts.conflictSettings;
parsedOptions.debug = opts.debug;
parsedOptions.throttel = opts.throttel;
parsedOptions.flags = opts.flags || 0;
if (!opts.filter) {
if (opts.matching) {
parsedOptions.filter = matcher_1.create(from, opts.matching);
}
else {
parsedOptions.filter = () => {
return true;
};
}
}
return parsedOptions;
};
// ---------------------------------------------------------
// Sync
// ---------------------------------------------------------
const checksBeforeCopyingSync = (from, to, options = {}) => {
if (!exists_1.sync(from)) {
throw errors_1.ErrDoesntExists(from);
}
if (exists_1.sync(to) && !options.overwrite) {
throw errors_1.ErrDestinationExists(to);
}
};
function copyFileSyncWithProgress(from, to, options = {}) {
return __awaiter(this, void 0, void 0, function* () {
return new Promise((resolve, reject) => {
const started = Date.now();
let cbCalled = false;
let elapsed = Date.now();
let speed = 0;
const done = (err) => {
if (!cbCalled) {
cbCalled = true;
resolve();
}
};
const rd = fs_1.createReadStream(from).
on('error', (err) => done(err));
const str = progress({
length: fs.statSync(from).size,
time: 100
}).on('progress', (e) => {
elapsed = (Date.now() - started) / 1000;
speed = e.transferred / elapsed;
options.writeProgress(from, e.transferred, e.length);
});
const wr = fs_1.createWriteStream(to);
wr.on('error', (err) => done(err));
wr.on('close', done);
rd.pipe(str).pipe(wr);
});
});
}
function copyFileSync(from, to, mode, options) {
return __awaiter(this, void 0, void 0, function* () {
const data = fs_1.readFileSync(from);
const writeOptions = {
mode: mode
};
if (options && options.writeProgress) {
yield copyFileSyncWithProgress(from, to, options);
}
else {
write_1.sync(to, data, writeOptions);
}
});
}
const copySymlinkSync = (from, to) => {
const symlinkPointsAt = fs.readlinkSync(from);
try {
fs_1.symlinkSync(symlinkPointsAt, to);
}
catch (err) {
// There is already file/symlink with this name on destination location.
// Must erase it manually, otherwise system won't allow us to place symlink there.
if (err.code === 'EEXIST') {
fs.unlinkSync(to);
// Retry...
fs.symlinkSync(symlinkPointsAt, to);
}
else {
throw err;
}
}
};
function copyItemSync(from, inspectData, to, options) {
return __awaiter(this, void 0, void 0, function* () {
const mode = mode_1.normalizeFileMode(inspectData.mode);
if (inspectData.type === interfaces_1.ENodeType.DIR) {
mkdirp.sync(to, { mode: parseInt(mode, 8), fs: null });
}
else if (inspectData.type === interfaces_1.ENodeType.FILE) {
yield copyFileSync(from, to, mode, options);
}
else if (inspectData.type === interfaces_1.ENodeType.SYMLINK) {
copySymlinkSync(from, to);
}
});
}
function sync(from, to, options) {
const opts = parseOptions(options, from);
checksBeforeCopyingSync(from, to, opts);
const nodes = [];
let sizeTotal = 0;
if (options && options.flags & interfaces_1.ECopyFlags.EMPTY) {
const dstStat = fs.statSync(to);
if (dstStat.isDirectory()) {
remove_1.sync(to);
}
}
// tslint:disable-next-line:no-shadowed-variable
const visitor = (path, inspectData) => {
if (opts.filter(path)) {
nodes.push({
path: path,
item: inspectData,
dst: pathUtil.resolve(to, pathUtil.relative(from, path))
});
sizeTotal += inspectData.size;
}
};
tree_walker_1.sync(from, {
inspectOptions: {
mode: true,
symlinks: true
}
}, visitor);
Promise.all(nodes.map((item, current) => __awaiter(this, void 0, void 0, function* () {
yield copyItemSync(item.path, item.item, item.dst, options);
if (opts.progress) {
opts.progress(item.path, current, nodes.length, item.item);
}
})));
}
exports.sync = sync;
// ---------------------------------------------------------
// Async
// ---------------------------------------------------------
/**
*
*
* @param {string} from
* @param {string} to
* @param {ICopyOptions} opts
* @returns {(Promise<IConflictSettings | any>)}
*/
const checkAsync = (from, to, opts) => {
return exists_1.async(from)
.then(srcPathExists => {
if (!srcPathExists) {
throw errors_1.ErrDoesntExists(from);
}
else {
return exists_1.async(to);
}
})
.then(destPathExists => {
if (destPathExists) {
if (opts.conflictSettings) {
return Promise.resolve(opts.conflictSettings);
}
if (opts.conflictCallback) {
const promise = opts.conflictCallback(to, inspect_1.createItem(to), interfaces_1.EError.EXISTS);
promise.then((settings) => {
settings.error = interfaces_1.EError.EXISTS;
});
return promise;
}
if (!opts.overwrite) {
throw errors_1.ErrDestinationExists(to);
}
}
});
};
const copyFileAsync = (from, to, mode, options, retriedAttempt) => {
return new Promise((resolve, reject) => {
const readStream = fs.createReadStream(from);
const writeStream = fs.createWriteStream(to, { mode: mode });
readStream.on('error', reject);
writeStream.on('error', (err) => {
const toDirPath = pathUtil.dirname(to);
// Force read stream to close, since write stream errored
// read stream serves us no purpose.
readStream.resume();
if (err.code === interfaces_1.EError.NOEXISTS && retriedAttempt === undefined) {
// Some parent directory doesn't exits. Create it and retry.
promisedMkdirp(toDirPath, null).then(() => {
// Make retry attempt only once to prevent vicious infinite loop
// (when for some obscure reason I/O will keep returning ENOENT error).
// Passing retriedAttempt = true.
copyFileAsync(from, to, mode, null, true)
.then(resolve)
.catch(reject);
});
}
else {
reject(err);
}
});
writeStream.on('finish', () => {
// feature: preserve times
if (options && options.flags & interfaces_1.ECopyFlags.PRESERVE_TIMES) {
const sourceStat = fs.statSync(from);
fs.open(to, 'w', (err, fd) => {
if (err) {
throw err;
}
fs.futimes(fd, sourceStat.atime, sourceStat.mtime, (err2) => {
if (err2) {
throw err2;
}
fs.close(fd, null);
resolve();
});
});
}
else {
resolve();
}
});
const size = fs.statSync(from).size;
let progressStream = null;
if (options && options.writeProgress && size > CPROGRESS_THRESHOLD) {
progressStream = progress({
length: fs.statSync(from).size,
time: 100 // call progress each 100 ms
});
let elapsed = Date.now();
let speed = 0;
const started = Date.now();
progressStream.on('progress', (e) => {
elapsed = (Date.now() - started) / 1000;
speed = e.transferred / elapsed;
options.writeProgress(from, e.transferred, e.length);
if (options.debug) {
console.log('write ' + from + ' (' + e.transferred + ' of ' + e.length);
}
});
if (options.throttel) {
readStream.pipe(progressStream).pipe(new throttle(options.throttel)).pipe(writeStream);
}
else {
readStream.pipe(progressStream).pipe(writeStream);
}
}
else {
if (options && options.debug) {
console.log('write ' + from + ' to ' + to);
}
readStream.pipe(writeStream);
}
});
};
function copySymlinkAsync(from, to) {
return promisedReadlink(from)
.then((symlinkPointsAt) => {
return new Promise((resolve, reject) => {
promisedSymlink(symlinkPointsAt, to, null)
.then(resolve)
.catch((err) => {
if (err.code === interfaces_1.EError.EXISTS) {
// There is already file/symlink with this name on destination location.
// Must erase it manually, otherwise system won't allow us to place symlink there.
promisedUnlink(to, null)
.then(() => {
return promisedSymlink(symlinkPointsAt, to, null);
})
.then(resolve, reject);
}
else {
reject(err);
}
});
});
});
}
exports.copySymlinkAsync = copySymlinkAsync;
const copyItemAsync = (from, inspectData, to, options) => {
const mode = mode_1.normalizeFileMode(inspectData.mode);
if (inspectData.type === interfaces_1.ENodeType.DIR) {
return promisedMkdirp(to, { mode: mode });
}
else if (inspectData.type === interfaces_1.ENodeType.FILE) {
return copyFileAsync(from, to, mode, options);
}
else if (inspectData.type === interfaces_1.ENodeType.SYMLINK) {
return copySymlinkAsync(from, to);
}
// EInspectItemType.OTHER
return Promise.resolve();
};
// handle user side setting "THROW" and non enum values (null)
const onConflict = (from, to, options, settings) => {
switch (settings.overwrite) {
case interfaces_1.EResolveMode.THROW: {
throw errors_1.ErrDestinationExists(to);
}
case interfaces_1.EResolveMode.OVERWRITE:
case interfaces_1.EResolveMode.APPEND:
case interfaces_1.EResolveMode.IF_NEWER:
case interfaces_1.EResolveMode.ABORT:
case interfaces_1.EResolveMode.IF_SIZE_DIFFERS:
case interfaces_1.EResolveMode.SKIP: {
return settings.overwrite;
}
default: {
return undefined;
}
}
};
function resolveConflict(from, to, options, resolveMode) {
if (resolveMode === undefined) {
return true;
}
const src = inspect_1.createItem(from);
const dst = inspect_1.createItem(to);
if (resolveMode === interfaces_1.EResolveMode.SKIP) {
return false;
}
else if (resolveMode === interfaces_1.EResolveMode.IF_NEWER) {
if (src.type === interfaces_1.ENodeType.DIR && dst.type === interfaces_1.ENodeType.DIR) {
return true;
}
if (dst.modifyTime.getTime() > src.modifyTime.getTime()) {
return false;
}
}
else if (resolveMode === interfaces_1.EResolveMode.IF_SIZE_DIFFERS) {
// @TODO : not implemented: copy EInspectItemType.DIR with ECopyResolveMode.IF_SIZE_DIFFERS
if (src.type === interfaces_1.ENodeType.DIR && dst.type === interfaces_1.ENodeType.DIR) {
return true;
}
else if (src.type === interfaces_1.ENodeType.FILE && dst.type === interfaces_1.ENodeType.FILE) {
if (src.size === dst.size) {
return false;
}
}
}
else if (resolveMode === interfaces_1.EResolveMode.OVERWRITE) {
return true;
}
else if (resolveMode === interfaces_1.EResolveMode.ABORT) {
return false;
}
}
exports.resolveConflict = resolveConflict;
function isDone(nodes) {
let done = true;
nodes.forEach((element) => {
if (element.status !== interfaces_1.ENodeOperationStatus.DONE) {
done = false;
}
});
return done;
}
/**
* A callback for treeWalkerStream. This is called when a node has been found.
*
* @param {string} from
* @param {string} to
* @param {*} vars
* @param {{ path: string, item: INode }} item
* @returns {Promise<void>}
*/
function visitor(from, to, vars, item) {
return __awaiter(this, void 0, void 0, function* () {
const options = vars.options;
let rel;
let destPath;
if (!item) {
return;
}
rel = pathUtil.relative(from, item.path);
destPath = pathUtil.resolve(to, rel);
item.status = interfaces_1.ENodeOperationStatus.PROCESSING;
const done = () => {
item.status = interfaces_1.ENodeOperationStatus.DONE;
if (isDone(vars.nodes)) {
return vars.resolve(vars.result);
}
};
if (isDone(vars.nodes)) {
return vars.resolve(vars.result);
}
vars.filesInProgress += 1;
// our main function after sanity checks
const checked = (subResolveSettings) => {
item.status = interfaces_1.ENodeOperationStatus.CHECKED;
// feature : report
if (subResolveSettings && options && options.flags && options.flags & interfaces_1.ECopyFlags.REPORT) {
vars.result.push({
error: subResolveSettings.error,
node: item,
resolved: subResolveSettings
});
}
if (subResolveSettings) {
// if the first resolve callback returned an individual resolve settings "THIS",
// ask the user again with the same item
const always = subResolveSettings.mode === interfaces_1.EResolve.ALWAYS;
if (always) {
options.conflictSettings = subResolveSettings;
}
let overwriteMode = subResolveSettings.overwrite;
overwriteMode = onConflict(item.path, destPath, options, subResolveSettings);
if (overwriteMode === interfaces_1.EResolveMode.ABORT) {
vars.abort = true;
}
if (vars.abort) {
return;
}
if (!resolveConflict(item.path, destPath, options, overwriteMode)) {
done();
return;
}
}
item.status = interfaces_1.ENodeOperationStatus.PROCESS;
copyItemAsync(item.path, item.item, destPath, options).then(() => {
vars.filesInProgress -= 1;
if (options.progress) {
if (options.progress(item.path, vars.filesInProgress, vars.filesInProgress, item.item) === false) {
vars.abort = true;
return vars.resolve();
}
}
done();
}).catch((err) => {
if (options && options.conflictCallback) {
if (err.code === interfaces_1.EError.PERMISSION || err.code === interfaces_1.EError.NOEXISTS) {
options.conflictCallback(item.path, inspect_1.createItem(destPath), err.code).then((errorResolveSettings) => {
// the user has set the conflict resolver to always, so we use the last one
if (vars.onCopyErrorResolveSettings) {
errorResolveSettings = vars.onCopyErrorResolveSettings;
}
// user said use this settings always, we track and use this last setting from now on
if (errorResolveSettings.mode === interfaces_1.EResolve.ALWAYS && !vars.onCopyErrorResolveSettings) {
vars.onCopyErrorResolveSettings = errorResolveSettings;
}
if (errorResolveSettings.overwrite === interfaces_1.EResolveMode.ABORT) {
vars.abort = true;
return vars.resolve();
}
if (errorResolveSettings.overwrite === interfaces_1.EResolveMode.THROW) {
vars.abort = true;
return vars.reject(err);
}
if (errorResolveSettings.overwrite === interfaces_1.EResolveMode.SKIP) {
vars.filesInProgress -= 1;
}
// user error, should never happen, unintended
if (errorResolveSettings.overwrite === interfaces_1.EResolveMode.IF_NEWER ||
errorResolveSettings.overwrite === interfaces_1.EResolveMode.IF_SIZE_DIFFERS ||
errorResolveSettings.overwrite === interfaces_1.EResolveMode.OVERWRITE) {
vars.reject(new interfaces_1.ErrnoException('settings make no sense : errorResolveSettings.overwrite = ' + errorResolveSettings.overwrite));
}
});
}
}
vars.reject(err);
});
};
return checkAsync(item.path, destPath, options).then(checked);
});
}
function next(nodes) {
for (let i = 0; i < nodes.length; i++) {
if (nodes[i].status === interfaces_1.ENodeOperationStatus.COLLECTED) {
return nodes[i];
}
}
return null;
}
/**
* Final async copy function.
* @export
* @param {string} from
* @param {string} to
* @param {ICopyOptions} [options]
* @returns
*/
function async(from, to, options) {
options = parseOptions(options, from);
return new Promise((resolve, reject) => {
checkAsync(from, to, options).then((resolver) => {
if (!resolver) {
resolver = options.conflictSettings || {
mode: interfaces_1.EResolve.THIS,
overwrite: interfaces_1.EResolveMode.OVERWRITE
};
}
else {
if (resolver.mode === interfaces_1.EResolve.ALWAYS) {
options.conflictSettings = resolver;
}
}
let overwriteMode = resolver.overwrite;
let result = void 0;
if (options && options.flags && options.flags & interfaces_1.ECopyFlags.REPORT) {
result = [];
}
// call onConflict to eventually throw an error
overwriteMode = onConflict(from, to, options, resolver);
// now evaluate the copy conflict settings and eventually abort
if (options && options.conflictSettings && !resolveConflict(from, to, options, overwriteMode)) {
return resolve();
}
// feature: clean before
if (options && options.flags & interfaces_1.ECopyFlags.EMPTY) {
const dstStat = fs.statSync(to);
if (dstStat.isDirectory()) {
remove_1.sync(to);
}
}
// walker variables
const visitorArgs = {
resolve: resolve,
reject: reject,
abort: false,
filesInProgress: 0,
resolveSettings: resolver,
options: options,
result: result,
nodes: [],
onCopyErrorResolveSettings: null
};
const nodes = visitorArgs.nodes;
// a function called when the treeWalkerStream or visitor has been finished
const process = function () {
visitorArgs.nodes = nodes;
if (isDone(nodes)) {
return resolve(result);
}
if (nodes.length) {
const item = next(nodes);
if (item) {
visitor(item.path, item.dst, visitorArgs, item).then(process);
}
}
};
let flags = interfaces_1.EInspectFlags.MODE;
if (options && options.flags && options.flags & interfaces_1.ECopyFlags.FOLLOW_SYMLINKS) {
flags |= interfaces_1.EInspectFlags.SYMLINKS;
}
iterator_1.async(from, {
filter: options.filter,
flags: flags
}).then((it) => {
let node = null;
while (node = it.next()) {
nodes.push({
path: node.path,
item: node.item,
dst: pathUtil.resolve(to, pathUtil.relative(from, node.path)),
status: interfaces_1.ENodeOperationStatus.COLLECTED
});
}
process();
});
}).catch(reject);
});
}
exports.async = async;
//# sourceMappingURL=copy.js.map

File diff suppressed because one or more lines are too long

7
packages/fs/build/dir.d.ts vendored Normal file
View File

@ -0,0 +1,7 @@
export interface IOptions {
empty?: boolean;
mode?: number | string;
}
export declare const validateInput: (methodName: string, path: string, options?: IOptions) => void;
export declare const sync: (path: string, options?: IOptions) => void;
export declare const async: (path: string, passedCriteria?: IOptions) => Promise<{}>;

190
packages/fs/build/dir.js Normal file
View File

@ -0,0 +1,190 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const pathUtil = require("path");
const fs_1 = require("fs");
const util_1 = require("util");
const fs = require("fs");
const remove_1 = require("./remove");
const mode_1 = require("./utils/mode");
const validate_1 = require("./utils/validate");
const errors_1 = require("./errors");
const interfaces_1 = require("./interfaces");
const mkdirp = require("mkdirp");
exports.validateInput = (methodName, path, options) => {
const methodSignature = methodName + '(path, [criteria])';
validate_1.validateArgument(methodSignature, 'path', path, ['string']);
validate_1.validateOptions(methodSignature, 'criteria', options, {
empty: ['boolean'],
mode: ['string', 'number']
});
};
const defaults = (options) => {
const result = options || {};
if (typeof result.empty !== 'boolean') {
result.empty = false;
}
if (result.mode !== undefined) {
result.mode = mode_1.normalizeFileMode(result.mode);
}
return result;
};
// ---------------------------------------------------------
// Sync
// ---------------------------------------------------------
const dirStatsSync = (path) => {
let stat;
try {
stat = fs_1.statSync(path);
}
catch (err) {
// Detection if path already exists
if (err.code !== interfaces_1.EError.NOEXISTS) {
throw err;
}
}
if (stat && !stat.isDirectory()) {
throw errors_1.ErrNoDirectory(path);
}
return stat;
};
function mkdirSync(path, criteria) {
mkdirp.sync(path, { mode: criteria.mode, fs: null });
}
;
function checkDirSync(path, stat, options) {
const checkMode = function () {
if (options.mode !== undefined) {
fs.chmodSync(path, options.mode);
}
};
const checkEmptiness = function () {
let list;
if (options.empty) {
// Delete everything inside this directory
list = fs_1.readdirSync(path);
list.forEach(function (filename) {
remove_1.sync(pathUtil.resolve(path, filename));
});
}
};
checkMode();
checkEmptiness();
}
;
exports.sync = (path, options) => {
const criteria = defaults(options);
const stat = dirStatsSync(path);
if (stat) {
checkDirSync(path, stat, criteria);
}
else {
mkdirSync(path, criteria);
}
};
// ---------------------------------------------------------
// Async
// ---------------------------------------------------------
const promisedStat = util_1.promisify(fs_1.stat);
const promisedReaddir = util_1.promisify(fs_1.readdir);
const dirStatAsync = (path) => {
return new Promise((resolve, reject) => {
promisedStat(path)
.then((stat) => {
if (stat.isDirectory()) {
resolve(stat);
}
else {
reject(errors_1.ErrNoDirectory(path));
}
})
.catch((err) => (err.code === interfaces_1.EError.NOEXISTS ? resolve(undefined) : reject(err)));
});
};
// Delete all files and directores inside given directory
const emptyAsync = (path) => {
return new Promise((resolve, reject) => {
promisedReaddir(path)
.then(function (list) {
const doOne = function (index) {
let subPath;
if (index === list.length) {
resolve();
}
else {
subPath = pathUtil.resolve(path, list[index]);
remove_1.async(subPath).then(() => doOne(index + 1));
}
};
doOne(0);
})
.catch(reject);
});
};
const checkMode = function (criteria, stat, path) {
if (criteria.mode !== undefined) {
return util_1.promisify(fs.chmod)(path, criteria.mode);
}
return Promise.resolve(null);
};
const checkDirAsync = (path, stat, options) => {
return new Promise((resolve, reject) => {
const checkEmptiness = function () {
if (options.empty) {
return emptyAsync(path);
}
return Promise.resolve();
};
checkMode(options, stat, path)
.then(checkEmptiness)
.then(resolve, reject);
});
};
const mkdirAsync = (path, criteria) => {
const options = criteria || {};
return new Promise((resolve, reject) => {
util_1.promisify(fs.mkdir)(path, options.mode)
.then(resolve)
.catch((err) => {
if (err.code === 'ENOENT') {
// Parent directory doesn't exist. Need to create it first.
mkdirAsync(pathUtil.dirname(path), options)
.then(() => {
// Now retry creating this directory.
return util_1.promisify(fs.mkdir)(path, options.mode);
})
.then(resolve)
.catch((err2) => {
if (err2.code === 'EEXIST') {
// Hmm, something other have already created the directory?
// No problem for us.
resolve();
}
else {
reject(err2);
}
});
}
else if (err.code === 'EEXIST') {
// The path already exists. We're fine.
resolve();
}
else {
reject(err);
}
});
});
};
exports.async = (path, passedCriteria) => {
const criteria = defaults(passedCriteria);
return new Promise((resolve, reject) => {
dirStatAsync(path)
.then((stat) => {
if (stat !== undefined) {
return checkDirAsync(path, stat, criteria);
}
return mkdirAsync(path, criteria);
})
.then(resolve, reject);
});
};
//# sourceMappingURL=dir.js.map

File diff suppressed because one or more lines are too long

7
packages/fs/build/errors.d.ts vendored Normal file
View File

@ -0,0 +1,7 @@
export declare const ErrNoFileOrDir: (path: string) => Error;
export declare const ErrCantDelete: (path: string) => Error;
export declare const ErrNotFile: (path: string) => Error;
export declare const ErrNoDirectory: (path: string) => Error;
export declare const ErrDoesntExists: (path: string) => Error;
export declare const ErrDestinationExists: (path: string) => Error;
export declare const ErrIsNotDirectory: (path: string) => Error;

View File

@ -0,0 +1,44 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const interfaces_1 = require("./interfaces");
const errno = require('errno');
Object.keys(errno.code).forEach(function (code) {
const e = errno.code[code];
exports[code] = (path) => {
let err = new Error(code + ', ' + e.description + (path ? ' \'' + path + '\'' : ''));
err.errno = e.errno;
err.code = code;
err.path = path;
return err;
};
});
exports.ErrNoFileOrDir = (path) => {
return new Error("Can't remove " + path + ' The path is not file nor directory');
};
exports.ErrCantDelete = (path) => {
return new Error("Can't remove " + path);
};
exports.ErrNotFile = (path) => {
return new Error('Path ' + path + ' exists but is not a file.' +
' Halting jetpack.file() call for safety reasons.');
};
exports.ErrNoDirectory = (path) => {
return new Error('Path ' + path + ' exists but is not a directory.' +
' Halting jetpack.dir() call for safety reasons.');
};
exports.ErrDoesntExists = (path) => {
const err = new Error("Path to copy doesn't exist " + path);
err.code = 'ENOENT';
return err;
};
exports.ErrDestinationExists = (path) => {
const err = new Error('Destination path already exists ' + path);
err.code = 'EEXIST';
return err;
};
exports.ErrIsNotDirectory = (path) => {
const err = new interfaces_1.ErrnoException('Path you want to find stuff in must be a directory ' + path);
err.code = 'ENOTDIR';
return err;
};
//#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AA,cAAc,GAAG,CAAC,IAAY,EAAS,EAAE;IACrD,MAAM,CAAC,IAAI,KAAK,CAAC,OAAO,GAAG,IAAI,GAAG,iCAAiC;QAClE,iDAAiD,CAAC,CAAC;AACrD,CAAC,CAAC;AAEW,QAAA,eAAe,GAAG,CAAC,IAAY,EAAS,EAAE;IACtD,MAAM,GAAG,GAAQ,IAAI,KAAK,CAAC,6BAA6B,GAAG,IAAI,CAAC,CAAC;IACjE,GAAG,CAAC,IAAI,GAAG,QAAQ,CAAC;IACpB,MAAM,CAAC,GAAG,CAAC;AACZ,CAAC,CAAC;AAEW,QAAA,oBAAoB,GAAG,CAAC,IAAY,EAAS,EAAE;IAC3D,MAAM,GAAG,GAAQ,IAAI,KAAK,CAAC,kCAAkC,GAAG,IAAI,CAAC,CAAC;IACtE,GAAG,CAAC,IAAI,GAAG,QAAQ,CAAC;IACpB,MAAM,CAAC,GAAG,CAAC;AACZ,CAAC,CAAC;AAEW,QAAA,iBAAiB,GAAG,CAAC,IAAY,EAAS,EAAE;IACxD,MAAM,GAAG,GAAG,IAAI,2BAAc,CAAC,qDAAqD,GAAG,IAAI,CAAC,CAAC;IAC7F,GAAG,CAAC,IAAI,GAAG,SAAS,CAAC;IACrB,MAAM,CAAC,GAAG,CAAC;AACZ,CAAC,CAAC"}

4
packages/fs/build/exists.d.ts vendored Normal file
View File

@ -0,0 +1,4 @@
import { ENodeType } from './interfaces';
export declare function validateInput(methodName: string, path: string): void;
export declare function sync(path: string): boolean | string;
export declare function async(path: string): Promise<boolean | string | ENodeType>;

View File

@ -0,0 +1,64 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const fs_1 = require("fs");
const validate_1 = require("./utils/validate");
const interfaces_1 = require("./interfaces");
function validateInput(methodName, path) {
const methodSignature = methodName + '(path)';
validate_1.validateArgument(methodSignature, 'path', path, ['string']);
}
exports.validateInput = validateInput;
;
// ---------------------------------------------------------
// Sync
// ---------------------------------------------------------
function sync(path) {
let stat;
try {
stat = fs_1.statSync(path);
if (stat.isDirectory()) {
return 'dir';
}
else if (stat.isFile()) {
return 'file';
}
return 'other';
}
catch (err) {
if (err.code !== 'ENOENT' && err.code !== 'ENOTDIR') {
throw err;
}
}
return false;
}
exports.sync = sync;
;
// ---------------------------------------------------------
// Async
// ---------------------------------------------------------
function async(path) {
return new Promise((resolve, reject) => {
fs_1.lstat(path, (err, stat) => {
if (err) {
if (err.code === 'ENOENT' || err.code === 'ENOTDIR') {
resolve(false);
}
else {
reject(err);
}
}
else if (stat.isDirectory()) {
resolve(interfaces_1.ENodeType.DIR);
}
else if (stat.isFile()) {
resolve(interfaces_1.ENodeType.FILE);
}
else {
resolve(interfaces_1.ENodeType.OTHER);
}
});
});
}
exports.async = async;
;
//# sourceMappingURL=exists.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"exists.js","sourceRoot":"","sources":["../src/exists.ts"],"names":[],"mappings":";;AAAA,2BAA4C;AAC5C,+CAAoD;AACpD,6CAAyD;AAEzD,uBAA8B,UAAkB,EAAE,IAAY;IAC7D,MAAM,eAAe,GAAG,UAAU,GAAG,QAAQ,CAAC;IAC9C,2BAAgB,CAAC,eAAe,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,QAAQ,CAAC,CAAC,CAAC;AAC7D,CAAC;AAHD,sCAGC;AAAA,CAAC;AAEF,4DAA4D;AAC5D,OAAO;AACP,4DAA4D;AAC5D,cAAqB,IAAY;IAChC,IAAI,IAAW,CAAC;IAChB,IAAI,CAAC;QACJ,IAAI,GAAG,aAAQ,CAAC,IAAI,CAAC,CAAC;QACtB,EAAE,CAAC,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC;YACxB,MAAM,CAAC,KAAK,CAAC;QACd,CAAC;QAAC,IAAI,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC;YAC1B,MAAM,CAAC,MAAM,CAAC;QACf,CAAC;QACD,MAAM,CAAC,OAAO,CAAC;IAChB,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
packages/fs/build/file.d.ts vendored Normal file
View File

@ -0,0 +1,10 @@
/// <reference types="node" />
export interface IOptions {
content: string | Buffer | Object | Array<any>;
jsonIndent: number;
mode: string;
}
export declare function validateInput(methodName: string, path: string, options?: IOptions): void;
export declare function defaults(passedCriteria: IOptions | null): IOptions;
export declare function sync(path: string, options: IOptions): void;
export declare function async(path: string, options: IOptions): Promise<{}>;

173
packages/fs/build/file.js Normal file
View File

@ -0,0 +1,173 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const fs = require("fs");
const Q = require('q');
const mode_1 = require("./utils/mode");
const validate_1 = require("./utils/validate");
const write_1 = require("./write");
const errors_1 = require("./errors");
const interfaces_1 = require("./interfaces");
const promisedStat = Q.denodeify(fs.stat);
const promisedChmod = Q.denodeify(fs.chmod);
function validateInput(methodName, path, options) {
const methodSignature = methodName + '(path, [criteria])';
validate_1.validateArgument(methodSignature, 'path', path, ['string']);
validate_1.validateOptions(methodSignature, 'criteria', options, {
content: ['string', 'buffer', 'object', 'array'],
jsonIndent: ['number'],
mode: ['string', 'number']
});
}
exports.validateInput = validateInput;
;
function defaults(passedCriteria) {
const criteria = passedCriteria || {};
if (criteria.mode !== undefined) {
criteria.mode = mode_1.normalizeFileMode(criteria.mode);
}
return criteria;
}
exports.defaults = defaults;
;
// ---------------------------------------------------------
// Sync
// ---------------------------------------------------------
const isFile = (path) => {
let stat;
try {
stat = fs.statSync(path);
}
catch (err) {
// Detection if path exists
if (err.code !== interfaces_1.EError.NOEXISTS) {
throw err;
}
}
if (stat && !stat.isFile()) {
throw errors_1.ErrNotFile(path);
}
return stat;
};
const checkContent = function (path, mode, options) {
if (options.content !== undefined) {
write_1.sync(path, options.content, {
mode: mode,
jsonIndent: options.jsonIndent
});
return true;
}
return false;
};
const checkMode = function (path, mode, options) {
if (options.mode !== undefined && options.mode !== mode) {
fs.chmodSync(path, options.mode);
}
};
const accept = (path, stat, options) => {
const mode = mode_1.normalizeFileMode(stat.mode);
if (!checkContent(path, mode, options)) {
checkMode(path, mode, options);
}
};
const touch = (path, options) => {
const content = options.content !== undefined ? options.content : '';
write_1.sync(path, content, {
mode: options.mode,
jsonIndent: options.jsonIndent
});
};
function sync(path, options) {
options = defaults(options);
const stat = isFile(path);
if (stat !== undefined) {
accept(path, stat, options);
}
else {
touch(path, options);
}
}
exports.sync = sync;
;
// ---------------------------------------------------------
// Async
// ---------------------------------------------------------
function isFileAsync(path) {
return new Promise((resolve, reject) => {
promisedStat(path)
.then((stat) => {
if ((stat).isFile()) {
resolve(stat);
}
else {
reject(errors_1.ErrNotFile(path));
}
})
.catch((err) => (err.code === interfaces_1.EError.NOEXISTS ? resolve(undefined) : reject(err)));
});
}
;
const checkModeAsync = (path, mode, options) => {
if (options.mode !== undefined && options.mode !== mode) {
return promisedChmod(path, options.mode);
}
return undefined;
};
const checkContentAsync = (path, mode, options) => {
return new Promise((resolve, reject) => {
if (options.content !== undefined) {
write_1.async(path, options.content, {
mode: mode,
jsonIndent: options.jsonIndent
}).then(() => resolve(true))
.catch(reject);
}
else {
resolve(false);
}
});
};
function writeAsync(path, stat, options) {
return __awaiter(this, void 0, void 0, function* () {
const mode = mode_1.normalizeFileMode(stat.mode);
return checkContentAsync(path, mode, options)
.then(contentReplaced => {
if (!contentReplaced) {
return checkModeAsync(path, mode, options);
}
return undefined;
});
});
}
;
const touchAsync = (path, options) => {
return write_1.async(path, options.content !== undefined ? options.content : '', {
mode: options.mode,
jsonIndent: options.jsonIndent
});
};
function async(path, options) {
return __awaiter(this, void 0, void 0, function* () {
return new Promise((resolve, reject) => {
options = defaults(options);
isFileAsync(path)
.then((stat) => {
if (stat !== undefined) {
return writeAsync(path, stat, options);
}
return touchAsync(path, options);
})
.then(resolve, reject);
});
});
}
exports.async = async;
;
//# sourceMappingURL=file.js.map

File diff suppressed because one or more lines are too long

10
packages/fs/build/find.d.ts vendored Normal file
View File

@ -0,0 +1,10 @@
export interface IOptions {
matching?: string[];
files?: boolean;
directories?: boolean;
recursive?: boolean;
cwd?: string;
}
export declare function validateInput(methodName: string, path: string, options?: IOptions): void;
export declare function sync(path: string, options: IOptions): string[];
export declare function async(path: string, options: IOptions): Promise<string[]>;

118
packages/fs/build/find.js Normal file
View File

@ -0,0 +1,118 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const pathUtil = require("path");
const tree_walker_1 = require("./utils/tree_walker");
const inspect_1 = require("./inspect");
const matcher_1 = require("./utils/matcher");
const validate_1 = require("./utils/validate");
const interfaces_1 = require("./interfaces");
const errors_1 = require("./errors");
function validateInput(methodName, path, options) {
const methodSignature = methodName + '([path], options)';
validate_1.validateArgument(methodSignature, 'path', path, ['string']);
validate_1.validateOptions(methodSignature, 'options', options, {
matching: ['string', 'array of string'],
files: ['boolean'],
directories: ['boolean'],
recursive: ['boolean']
});
}
exports.validateInput = validateInput;
;
const defaults = (options) => {
let opts = options || {};
// defaults:
if (opts.files === undefined) {
opts.files = true;
}
if (opts.directories === undefined) {
opts.directories = false;
}
if (opts.recursive === undefined) {
opts.recursive = true;
}
return opts;
};
const processFoundObjects = (foundObjects, cwd) => {
return foundObjects.map((inspectObj) => {
return pathUtil.relative(cwd, inspectObj.absolutePath);
});
};
// ---------------------------------------------------------
// Sync
// ---------------------------------------------------------
function findSync(path, options) {
const foundInspectObjects = [];
const matchesAnyOfGlobs = matcher_1.create(path, options.matching);
tree_walker_1.sync(path, {
maxLevelsDeep: options.recursive ? Infinity : 1,
inspectOptions: {
absolutePath: true
}
}, (itemPath, item) => {
if (itemPath !== path && matchesAnyOfGlobs(itemPath)) {
if ((item.type === interfaces_1.ENodeType.FILE && options.files === true)
|| (item.type === interfaces_1.ENodeType.DIR && options.directories === true)) {
foundInspectObjects.push(item);
}
}
});
return processFoundObjects(foundInspectObjects, options.cwd);
}
;
function sync(path, options) {
const entryPointInspect = inspect_1.sync(path);
if (entryPointInspect === undefined) {
throw errors_1.ErrDoesntExists(path);
}
else if (entryPointInspect.type !== 'dir') {
throw errors_1.ErrIsNotDirectory(path);
}
return findSync(path, defaults(options));
}
exports.sync = sync;
;
// ---------------------------------------------------------
// Async
// ---------------------------------------------------------
function findAsync(path, options) {
return new Promise((resolve, reject) => {
const foundInspectObjects = [];
const matchesAnyOfGlobs = matcher_1.create(path, options.matching);
const walker = tree_walker_1.stream(path, {
maxLevelsDeep: options.recursive ? Infinity : 1,
inspectOptions: {
absolutePath: true
}
}).on('readable', () => {
const data = walker.read();
let item;
if (data && data.path !== path && matchesAnyOfGlobs(data.path)) {
item = data.item;
if ((item.type === interfaces_1.ENodeType.FILE && options.files === true)
|| (item.type === interfaces_1.ENodeType.DIR && options.directories === true)) {
foundInspectObjects.push(item);
}
}
}).on('error', reject)
.on('end', () => {
resolve(processFoundObjects(foundInspectObjects, options.cwd));
});
});
}
;
function async(path, options) {
return inspect_1.async(path)
.then(entryPointInspect => {
if (entryPointInspect === undefined) {
throw errors_1.ErrDoesntExists(path);
}
else if (entryPointInspect.type !== interfaces_1.ENodeType.DIR) {
throw errors_1.ErrIsNotDirectory(path);
}
return findAsync(path, defaults(options));
});
}
exports.async = async;
;
//# sourceMappingURL=find.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"find.js","sourceRoot":"","sources":["../src/find.ts"],"names":[],"mappings":";;AAAA,iCAAkC;AAClC,qDAAyF;AACzF,uCAAuE;AACvE,6CAAoD;AACpD,+CAAqE;AACrE,6CAAgD;AAChD,qCAA8D;AAS9D,uBAA8B,UAAkB,EAAE,IAAY,EAAE,OAAkB;IACjF,MAAM,eAAe,GAAG,UAAU,GAAG,mBAAmB,CAAC;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pB,EAAE,CAAC,KAAK,EAAE,GAAG,EAAE;YACf,OAAO,CAAC,mBAAmB,CAAC,mBAAmB,EAAE,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC;QAChE,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACJ,CAAC;AAAA,CAAC;AAEF,eAAsB,IAAY,EAAE,OAAiB;IACpD,MAAM,CAAC,eAAY,CAAC,IAAI,CAAC;SACvB,IAAI,CAAC,iBAAiB,CAAC,EAAE;QACzB,EAAE,CAAC,CAAC,iBAAiB,KAAK,SAAS,CAAC,CAAC,CAAC;YACrC,MAAM,wBAAe,CAAC,IAAI,CAAC,CAAC;QAC7B,CAAC;QAAC,IAAI,CAAC,EAAE,CAAC,CAAE,iBAAyB,CAAC,IAAI,KAAK,sBAAS,CAAC,GAAG,CAAC,CAAC,CAAC;YAC9D,MAAM,0BAAiB,CAAC,IAAI,CAAC,CAAC;QAC/B,CAAC;QACD,MAAM,CAAC,SAAS,CAAC,IAAI,EAAE,QAAQ,CAAC,OAAO,CAAC,CAAC,CAAC;IAC3C,CAAC,CAAC,CAAC;AACL,CAAC;AAVD,sBAUC;AAAA,CAAC"}

10
packages/fs/build/imports.d.ts vendored Normal file
View File

@ -0,0 +1,10 @@
export declare const file: {
write_atomic: any;
};
export declare const json: {
parse: (text: string, reviver?: (key: any, value: any) => any) => any;
serialize: {
(value: any, replacer?: (key: string, value: any) => any, space?: string | number): string;
(value: any, replacer?: (string | number)[], space?: string | number): string;
};
};

View File

@ -0,0 +1,11 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const write_fs = require('write-file-atomic');
exports.file = {
write_atomic: write_fs
};
exports.json = {
parse: JSON.parse,
serialize: JSON.stringify
};
//# sourceMappingURL=imports.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"imports.js","sourceRoot":"","sources":["../src/imports.ts"],"names":[],"mappings":";;AAAA,MAAM,QAAQ,GAAG,OAAO,CAAC,mBAAmB,CAAC,CAAC;AACjC,QAAA,IAAI,GAAG;IAClB,YAAY,EAAE,QAAQ;CACvB,CAAC;AACW,QAAA,IAAI,GAAG;IAClB,KAAK,EAAE,IAAI,CAAC,KAAK;IACjB,SAAS,EAAE,IAAI,CAAC,SAAS;CAC1B,CAAC"}

7
packages/fs/build/inspect.d.ts vendored Normal file
View File

@ -0,0 +1,7 @@
import { INode, IInspectOptions } from './interfaces';
export declare const supportedChecksumAlgorithms: string[];
export declare function DefaultInspectOptions(): IInspectOptions;
export declare function validateInput(methodName: string, path: string, options?: IInspectOptions): void;
export declare function createItem(path: string, options?: IInspectOptions): INode;
export declare function sync(path: string, options?: IInspectOptions): INode;
export declare function async(path: string, options?: IInspectOptions): Promise<INode>;

View File

@ -0,0 +1,271 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const fs_1 = require("fs");
const mime_1 = require("mime");
const pathUtil = require("path");
const validate_1 = require("./utils/validate");
const crypto_1 = require("crypto");
const interfaces_1 = require("./interfaces");
const Q = require('q');
const denodeify = require("denodeify");
exports.supportedChecksumAlgorithms = ['md5', 'sha1', 'sha256', 'sha512'];
const promisedStat = denodeify(fs_1.stat);
const promisedLstat = denodeify(fs_1.lstat);
const promisedReadlink = denodeify(fs_1.readlink);
/*
const _async = require('async');
export async function size(item, ignoreRegEx?: boolean, callback?: any) {
return new Promise((resolve, reject) => {
let cb;
let ignoreRegExp;
if (!callback) {
cb = ignoreRegEx;
ignoreRegExp = null;
} else {
cb = callback;
ignoreRegExp = ignoreRegEx;
}
lstat(item, function lstat(e, stats) {
let total = !e ? (stats.size || 0) : 0;
if (!e && stats.isDirectory()) {
readdir(item, function readdir(err, list) {
if (err) { reject(err); }
_async.forEach(
list,
function iterate(dirItem, next) {
size(
pathUtil.join(item, dirItem),
ignoreRegExp,
function readSize(error, size) {
if (!error) { total += size; }
next(error);
}
);
},
function done(finalErr) {
resolve({ error: finalErr, total: total });
}
);
});
} else {
if (ignoreRegExp && ignoreRegExp.test(item)) {
total = 0;
}
resolve({ error: e, total: total });
}
});
});
}
export async function sizea(item, ignoreRegEx?: boolean, callback?: any) {
return new Promise((resolve, reject) => {
let cb;
let ignoreRegExp;
if (!callback) {
cb = ignoreRegEx;
ignoreRegExp = null;
} else {
cb = callback;
ignoreRegExp = ignoreRegEx;
}
const stats = lstatSync(item);
let total = (stats.size || 0);
if (stats.isDirectory()) {
const list = readdirSync(item);
_async.forEach(
list,
function iterate(dirItem, next) {
size(
pathUtil.join(item, dirItem),
ignoreRegExp,
function readSize(error, size) {
if (!error) { total += size; }
next(error);
}
);
},
function done(finalErr) {
resolve({ error: finalErr, total: total });
}
);
} else {
if (ignoreRegExp && ignoreRegExp.test(item)) {
total = 0;
}
return { total: total };
}
});
}
*/
function DefaultInspectOptions() {
return {
times: true,
mode: true
};
}
exports.DefaultInspectOptions = DefaultInspectOptions;
function validateInput(methodName, path, options) {
const methodSignature = methodName + '(path, [options])';
validate_1.validateArgument(methodSignature, 'path', path, ['string']);
validate_1.validateOptions(methodSignature, 'options', options, {
checksum: ['string'],
mode: ['boolean'],
times: ['boolean'],
absolutePath: ['boolean'],
symlinks: ['boolean'],
size: 'number',
mime: 'string'
});
if (options && options.checksum !== undefined
&& exports.supportedChecksumAlgorithms.indexOf(options.checksum) === -1) {
throw new Error('Argument "options.checksum" passed to ' + methodSignature
+ ' must have one of values: ' + exports.supportedChecksumAlgorithms.join(', '));
}
}
exports.validateInput = validateInput;
const createInspectObj = (path, options, stat) => {
const obj = {};
obj.name = pathUtil.basename(path);
if (stat.isFile()) {
obj.type = interfaces_1.ENodeType.FILE;
obj.size = stat.size;
}
else if (stat.isDirectory()) {
obj.type = interfaces_1.ENodeType.DIR;
}
else if (stat.isSymbolicLink()) {
obj.type = interfaces_1.ENodeType.SYMLINK;
}
else {
obj.type = interfaces_1.ENodeType.OTHER;
}
if (options.mode) {
obj.mode = stat.mode;
}
if (options.mime) {
if (stat.isDirectory()) {
obj.mime = 'inode/directory';
}
else if (stat.isBlockDevice()) {
obj.mime = 'inode/blockdevice';
}
else if (stat.isCharacterDevice()) {
obj.mime = 'inode/chardevice';
}
else if (stat.isSymbolicLink()) {
obj.mime = 'inode/symlink';
}
else if (stat.isFIFO()) {
obj.mime = 'inode/fifo';
}
else if (stat.isSocket()) {
obj.mime = 'inode/socket';
}
else {
obj.mime = mime_1.getType(path);
}
}
if (options.times) {
obj.accessTime = stat.atime;
obj.modifyTime = stat.mtime;
obj.changeTime = stat.ctime;
}
if (options.absolutePath) {
obj.absolutePath = path;
}
return obj;
};
function createItem(path, options) {
options = options || DefaultInspectOptions();
const stat = (options.symlinks ? fs_1.lstatSync : fs_1.statSync)(path);
return createInspectObj(path, options, stat);
}
exports.createItem = createItem;
// ---------------------------------------------------------
// Sync
// ---------------------------------------------------------
const fileChecksum = (path, algo) => {
const hash = crypto_1.createHash(algo);
const data = fs_1.readFileSync(path);
hash.update(data);
return hash.digest('hex');
};
const addExtraFieldsSync = (path, inspectObj, options) => {
if (inspectObj.type === interfaces_1.ENodeType.FILE && options.checksum) {
inspectObj[options.checksum] = fileChecksum(path, options.checksum);
}
else if (inspectObj.type === interfaces_1.ENodeType.SYMLINK) {
inspectObj.pointsAt = fs_1.readlinkSync(path);
}
return inspectObj;
};
function sync(path, options) {
let stat;
options = options || {};
try {
stat = (options.symlinks ? fs_1.lstatSync : fs_1.statSync)(path);
}
catch (err) {
// Detection if path exists
if (err.code === 'ENOENT') {
// Doesn't exist. Return undefined instead of throwing.
return undefined;
}
throw err;
}
return addExtraFieldsSync(path, createInspectObj(path, options, stat), options);
}
exports.sync = sync;
// ---------------------------------------------------------
// Async
// ---------------------------------------------------------
function fileChecksumAsync(path, algo) {
return __awaiter(this, void 0, void 0, function* () {
const deferred = Q.defer();
const hash = crypto_1.createHash(algo);
const s = fs_1.createReadStream(path);
s.on('data', (data) => hash.update(data));
s.on('end', () => deferred.resolve(hash.digest('hex')));
s.on('error', (e) => deferred.reject(e));
return deferred.promise;
});
}
const addExtraFieldsAsync = (path, inspectObj, options) => {
if (inspectObj.type === interfaces_1.ENodeType.FILE && options.checksum) {
return fileChecksumAsync(path, options.checksum)
.then(checksum => {
inspectObj[options['checksum']] = checksum;
return inspectObj;
});
}
else if (inspectObj.type === interfaces_1.ENodeType.SYMLINK) {
return promisedReadlink(path)
.then(linkPath => {
inspectObj.pointsAt = linkPath;
return inspectObj;
});
}
return new Q(inspectObj);
};
function async(path, options) {
return new Promise((resolve, reject) => {
options = options || {};
(options.symlinks ? promisedLstat : promisedStat)(path)
.then((stat) => {
addExtraFieldsAsync(path, createInspectObj(path, options, stat), options).then(resolve, reject);
})
.catch(err => (err.code === 'ENOENT' ? resolve(undefined) : reject(err)));
});
}
exports.async = async;
//# sourceMappingURL=inspect.js.map

File diff suppressed because one or more lines are too long

9
packages/fs/build/inspect_tree.d.ts vendored Normal file
View File

@ -0,0 +1,9 @@
import { INode } from './interfaces';
export interface Options {
checksum: string;
relativePath: boolean;
symlinks: boolean;
}
export declare function validateInput(methodName: string, path: string, options: Options): void;
export declare function sync(path: string, options?: any): any | undefined;
export declare function async(path: string, options?: Options): Promise<INode>;

View File

@ -0,0 +1,140 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const crypto_1 = require("crypto");
const pathUtil = require("path");
const inspect_1 = require("./inspect");
const interfaces_1 = require("./interfaces");
const list_1 = require("./list");
const validate_1 = require("./utils/validate");
const Q = require('q');
function validateInput(methodName, path, options) {
const methodSignature = methodName + '(path, options)';
validate_1.validateArgument(methodSignature, 'path', path, ['string']);
validate_1.validateOptions(methodSignature, 'options', options, {
checksum: ['string'],
relativePath: ['boolean']
});
if (options && options.checksum !== undefined
&& inspect_1.supportedChecksumAlgorithms.indexOf(options.checksum) === -1) {
throw new Error('Argument "options.checksum" passed to ' + methodSignature
+ ' must have one of values: ' + inspect_1.supportedChecksumAlgorithms.join(', '));
}
}
exports.validateInput = validateInput;
;
function generateTreeNodeRelativePath(parent, path) {
if (!parent) {
return '.';
}
return parent.relativePath + '/' + pathUtil.basename(path);
}
;
// Creates checksum of a directory by using
// checksums and names of all its children inside.
const checksumOfDir = (inspectList, algo) => {
const hash = crypto_1.createHash(algo);
inspectList.forEach(function (inspectObj) {
hash.update(inspectObj.name + inspectObj[algo]);
});
return hash.digest('hex');
};
// ---------------------------------------------------------
// Sync
// ---------------------------------------------------------
function inspectTreeNodeSync(path, options, parent) {
const treeBranch = inspect_1.sync(path, { checksum: options.checksum, symlinks: options.symlinks });
if (treeBranch) {
if (options.relativePath) {
treeBranch.relativePath = generateTreeNodeRelativePath(parent, path);
}
if (treeBranch.type === interfaces_1.ENodeType.DIR /*|| (options.symlinks && treeBranch.type === 'symlink')*/) {
treeBranch.size = 0;
treeBranch.children = (list_1.sync(path) || []).map(function (filename) {
let subBranchPath = pathUtil.join(path, filename);
let treeSubBranch = inspectTreeNodeSync(subBranchPath, options, treeBranch);
// Add together all childrens' size to get directory combined size.
treeBranch.size += treeSubBranch.size || 0;
//treeBranch.total += treeSubBranch.total;
return treeSubBranch;
});
if (options.checksum) {
treeBranch[options.checksum] = checksumOfDir(treeBranch.children, options.checksum);
}
}
}
return treeBranch;
}
;
function sync(path, options) {
options = options || {};
options.symlinks = true;
return inspectTreeNodeSync(path, options, undefined);
}
exports.sync = sync;
;
// ---------------------------------------------------------
// Async
// ---------------------------------------------------------
function inspectTreeNodeAsync(path, options, parent) {
return new Promise((resolve, reject) => {
const inspectAllChildren = (treeBranch) => {
return new Promise((resolve, reject) => {
list_1.async(path).then((children) => {
const doNext = (index) => {
let subPath;
if (index === children.length) {
if (options.checksum) {
// We are done, but still have to calculate checksum of whole directory.
treeBranch[options.checksum] = checksumOfDir(treeBranch.children, options.checksum);
}
resolve();
}
else {
subPath = pathUtil.join(path, children[index]);
inspectTreeNodeAsync(subPath, options, treeBranch)
.then((treeSubBranch) => {
children[index] = treeSubBranch;
treeBranch.size += treeSubBranch.size || 0;
doNext(index + 1);
})
.catch(reject);
}
};
treeBranch.children = children;
treeBranch.size = 0;
doNext(0);
});
});
};
inspect_1.async(path, options)
.then((treeBranch) => {
if (!treeBranch) {
// Given path doesn't exist. We are done.
resolve(treeBranch);
}
else {
if (options.relativePath) {
treeBranch.relativePath = generateTreeNodeRelativePath(parent, path);
}
if (treeBranch.type !== interfaces_1.ENodeType.DIR) {
resolve(treeBranch);
}
else {
inspectAllChildren(treeBranch)
.then(() => resolve(treeBranch))
.catch(reject);
}
}
})
.catch(reject);
});
}
;
function async(path, options) {
options = options || {};
options.symlinks = true;
return inspectTreeNodeAsync(path, options);
}
exports.async = async;
;
//# sourceMappingURL=inspect_tree.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"inspect_tree.js","sourceRoot":"","sources":["../src/inspect_tree.ts"],"names":[],"mappings":";;AAAA,mCAAoC;AACpC,iCAAkC;AAClC,uCAAoG;AACpG,6CAAiE;AACjE,iCAA8D;AAC9D,+CAAqE;AACrE,MAAM,CAAC,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC;AAQvB,uBAA8B,UAAkB,EAAE,IAAY,EAAE,OAAgB;IAC9E,MAAM,eAAe,GAAG,UAAU,GAAG,iBAAiB,CAAC;IACvD,2BAAgB,CAAC,eAAe,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,QAAQ,CAAC,CAAC,CAAC;IAC5D,0BAAe,CAAC,eAAe,EAAE,SAAS,EAAE,OAAO,EAAE;QACnD,QAAQ,EAAE,CAAC,QAAQ,CAAC;QACpB,YAAY,EAAE,CAAC,SAAS,CAAC;KAC1B,CAAC,CAAC;IAEH,EAAE,CAAC,CAAC,OAAO,IAAI,OAAO,CAAC,QAAQ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/>
export declare enum ENodeType {
FILE,
DIR,
SYMLINK,
OTHER,
BLOCK,
}
/**
* Native errors.
* @todo : replace with errno.
*/
export declare let EError: any;
export interface INode {
name: string;
type: ENodeType | string;
size?: number;
accessTime?: Date;
modifyTime?: Date;
changeTime?: Date;
absolutePath?: string;
mode?: number;
pointsAt?: string;
relativePath?: string;
children?: INode[];
total?: number;
checksum?: string;
mime?: string;
}
/**
* The options for "inspect".
*
* @export
* @interface IInspectOptions
*/
export interface IInspectOptions {
checksum?: string;
mode?: boolean;
times?: boolean;
absolutePath?: boolean;
symlinks?: boolean;
size?: boolean;
mime?: boolean;
}
export interface INodeReport {
node: IProcessingNode;
error: string;
resolved: IConflictSettings;
}
/**
* The accepted types for write and read as union.
*/
export declare type ReadWriteDataType = string | Buffer | Object;
/**
* An extented version of Error to make typescript happy. This has been copied from
* the official Node typings.
*
* @export
* @class ErrnoException
* @extends {Error}
*/
export declare class ErrnoException extends Error {
errno?: number;
code?: string;
path?: string;
syscall?: string;
stack?: string;
}
/**
* Structure for file operations.
*/
export interface IProcessingNode {
path: string;
item: INode;
status?: ENodeOperationStatus;
dst?: string;
}
/**
* Basic flags during a file operation.
*
* @export
* @enum {number}
*/
export declare enum EBaseFlags {
/**
* When copying, don't copy symlinks but resolve them instead.
*/
FOLLOW_SYMLINKS = 8,
}
/**
* Flags to determine certain properties during inspection.
*
* @export
* @enum {number}
*/
export declare enum EInspectFlags {
MODE = 2,
TIMES = 4,
SYMLINKS = 8,
FILE_SIZE = 16,
DIRECTORY_SIZE = 32,
CHECKSUM = 64,
MIME = 128,
}
/**
* Basic options for file operations: used by cp, mv, rename and rm.
*
* @export
* @interface IBaseOptions
*/
export interface IBaseOptions {
/**
* Array of glob minimatch patterns
*
* @type {string[]}
* @memberOf IBaseOptions
*/
matching?: string[];
/**
* A function called to reject or accept nodes. This is used only when matching
* has been left empty.
* @memberOf IBaseOptions
*/
filter?: (from: string) => boolean;
/**
* Flags to determine properties per node
*
* @type {EInspectFlags}
* @memberOf IBaseOptions
*/
flags?: EInspectFlags;
}
/**
* Callback prototype signature when an item has been copied.
* This is used to abort the copy process when returning false.
*
* @param {string} path The path of the item.
* @param {number} current The current index of the item.
* @param {number} total The total of all items.
* @param {INode} [item] The node data for the item.
* @returns {boolean}
*/
export declare type ItemProgressCallback = (path: string, current: number, total: number, item?: INode) => boolean;
/**
* Callback prototype signature when an item conflict occurs.
* It's async since the conflict might be resolved in an client application and hence
* we have to wait til the user decided.
*
* This is not being called if:
* - a previous callback returned with IConflictSettings#mode == ALWAYS
* - the options object already contains pre-defined conflict settings.
*
* @param {string} path The path of the item.
* @param {INode} item The node data.
* @param {string} err The native error code of the conflict (EEXIST,...)
* @returns {Promise<IConflictSettings>}
*/
export declare type ResolveConflictCallback = (path: string, item: INode, err: string) => Promise<IConflictSettings>;
/**
* Callback prototype signature when a file with at least 5MB size is being copied.
*
* @param {string} path The path of the item.
* @param {number} current The current copied bytes.
* @param {number} total The total size in bytes.
* @returns {Promise<IConflictSettings>}
*/
export declare type WriteProgressCallback = (path: string, current: number, total: number) => void;
/**
* Status of a node operation.
*
* @export
* @enum {number}
*/
export declare enum ENodeOperationStatus {
COLLECTED = 0,
CHECKED = 1,
PROCESSING = 2,
PROCESS = 3,
ASKING = 4,
ANSWERED = 5,
DONE = 6,
}
/**
* The possible modes to resolve a conflict during copy and move.
*
* @export
* @enum {number}
*/
export declare enum EResolveMode {
SKIP = 0,
OVERWRITE = 1,
IF_NEWER = 2,
IF_SIZE_DIFFERS = 3,
APPEND = 4,
THROW = 5,
RETRY = 6,
ABORT = 7,
}
/**
* Additional flags for copy
*
* @export
* @enum {number}
*/
export declare enum ECopyFlags {
/**
* Transfer atime and mtime of source to target
*/
PRESERVE_TIMES = 2,
/**
* Empty the target folder
*/
EMPTY = 4,
/**
* When copying, don't copy symlinks but resolve them instead.
*/
FOLLOW_SYMLINKS = 8,
/**
* Collect errors & success
*/
REPORT = 16,
}
/**
* Copy options
*
* @export
* @interface ICopyOptions
*/
export interface ICopyOptions {
/**
* @type {boolean}
* @deprecated Use conflict callback instead.
* @memberOf ICopyOptions
*/
overwrite?: boolean;
/**
* Array of glob minimatch patterns
*
* @type {string[]}
* @memberOf ICopyOptions
*/
matching?: string[];
/**
* A function called to reject or accept nodes to be copied. This is used only when matching
* has been left empty.
* @memberOf ICopyOptions
*/
filter?: (from: string) => boolean;
/**
* A progress callback for any copied item. Only excecuted in async.
*/
progress?: ItemProgressCallback;
/**
* A progress function called for async and larger files only.
*
* @type {WriteProgressCallback}
* @memberOf ICopyOptions
*/
writeProgress?: WriteProgressCallback;
/**
* A callback when a conflict or error occurs. This is being called only if the user
* didn't provide conflictSettings.
*
* @type {ResolveConflictCallback}
* @memberOf ICopyOptions
*/
conflictCallback?: ResolveConflictCallback;
/**
* Ability to set conflict resolver settings in advance, so that no callback will be called.
*
* @type {IConflictSettings}
* @memberOf ICopyOptions
*/
conflictSettings?: IConflictSettings;
/**
* Throttel copy for larger files. This will be only used when writeProgress is set and the file is at least 5MB.
*
* @type {number}
* @memberOf ICopyOptions
*/
throttel?: number;
/**
* Print some debug messages.
*
* @type {boolean}
* @memberOf ICopyOptions
*/
debug?: boolean;
/**
* The copy flags.
*
* @type {ECopyFlags}
* @memberOf ICopyOptions
*/
flags?: ECopyFlags;
}
/**
* An enumeration to narrow a conflict resolve to a single item or for all following conflicts.
*
* @export
* @enum {number}
*/
export declare enum EResolve {
/**
* Always will use the chose conflict settings for all following conflicts.
*/
ALWAYS = 0,
/**
* 'This' will use the conflict settings for a single conflict so the conflict callback will be triggered again for the next conflict.
*/
THIS = 1,
}
/**
* A composite conflict settings and it's scope. This is the result type
* for the conflict callback.
*
* @export
* @interface IConflictSettings
*/
export interface IConflictSettings {
/**
* How to resolve this conflict/error.
*
* @type {EResolveMode}
* @memberOf IConflictSettings
*/
overwrite: EResolveMode;
/**
* The scope of this conflict resolver: always or this.
*
* @type {EResolve}
* @memberOf IConflictSettings
*/
mode: EResolve;
/**
* Track the origin error type for this settings.
*
* @type {string}
* @memberOf IConflictSettings
*/
error?: string;
}
export declare type TCopyResult = void | INodeReport[];
/**
* fs/write options.
*
* @export
* @interface IWriteOptions
*/
export interface IWriteOptions {
atomic?: boolean;
jsonIndent?: number;
mode?: string;
}
export declare type TDeleteResult = void | INodeReport[];
/**
* Additional flags for delete
*
* @export
* @enum {number}
*/
export declare enum EDeleteFlags {
REPORT = 16,
}
/**
* Delete options
*
* @export
* @interface IDeleteOptions
*/
export interface IDeleteOptions {
/**
* Array of glob minimatch patterns
*
* @type {string[]}
* @memberOf IDeleteOptions
*/
matching?: string[];
/**
* A callback when a conflict or error occurs. This is being called only if the user
* didn't provide conflictSettings.
*
* @type {ResolveConflictCallback}
* @memberOf IDeleteOptions
*/
conflictCallback?: ResolveConflictCallback;
/**
* Ability to set conflict resolver settings in advance, so that no callback will be called.
*
* @type {IConflictSettings}
* @memberOf IDeleteOptions
*/
conflictSettings?: IConflictSettings;
/**
*
* A progress callback for any deleted item. Only excecuted in async.
* @type {ItemProgressCallback}
* @memberOf IDeleteOptions
*/
progress?: ItemProgressCallback;
/**
* Print some messages.
*
* @type {boolean}
* @memberOf IDeleteOptions
*/
debug?: boolean;
/**
* A function called to reject or accept nodes to be copied. This is used only when matching
* has been left empty.
* @memberOf IDeleteOptions
*/
filter?: (from: string) => boolean;
/**
* Move files to system's trash/recycle-bin
*
* @type {boolean}
* @memberOf IDeleteOptions
*/
trash?: boolean;
flags?: EDeleteFlags;
}

View File

@ -0,0 +1,158 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/////////////////////////////////////////////////////////
//
// Enums
//
var ENodeType;
(function (ENodeType) {
ENodeType[ENodeType["FILE"] = 'file'] = "FILE";
ENodeType[ENodeType["DIR"] = 'dir'] = "DIR";
ENodeType[ENodeType["SYMLINK"] = 'symlink'] = "SYMLINK";
ENodeType[ENodeType["OTHER"] = 'other'] = "OTHER";
ENodeType[ENodeType["BLOCK"] = 'block'] = "BLOCK";
})(ENodeType = exports.ENodeType || (exports.ENodeType = {}));
/**
* Native errors.
* @todo : replace with errno.
*/
exports.EError = {
NONE: 'None',
EXISTS: 'EEXIST',
PERMISSION: 'EACCES',
NOEXISTS: 'ENOENT',
CROSS_DEVICE: 'EXDEV'
};
/**
* An extented version of Error to make typescript happy. This has been copied from
* the official Node typings.
*
* @export
* @class ErrnoException
* @extends {Error}
*/
class ErrnoException extends Error {
}
exports.ErrnoException = ErrnoException;
/**
* Basic flags during a file operation.
*
* @export
* @enum {number}
*/
var EBaseFlags;
(function (EBaseFlags) {
/**
* When copying, don't copy symlinks but resolve them instead.
*/
EBaseFlags[EBaseFlags["FOLLOW_SYMLINKS"] = 8] = "FOLLOW_SYMLINKS";
})(EBaseFlags = exports.EBaseFlags || (exports.EBaseFlags = {}));
/**
* Flags to determine certain properties during inspection.
*
* @export
* @enum {number}
*/
var EInspectFlags;
(function (EInspectFlags) {
EInspectFlags[EInspectFlags["MODE"] = 2] = "MODE";
EInspectFlags[EInspectFlags["TIMES"] = 4] = "TIMES";
EInspectFlags[EInspectFlags["SYMLINKS"] = 8] = "SYMLINKS";
EInspectFlags[EInspectFlags["FILE_SIZE"] = 16] = "FILE_SIZE";
EInspectFlags[EInspectFlags["DIRECTORY_SIZE"] = 32] = "DIRECTORY_SIZE";
EInspectFlags[EInspectFlags["CHECKSUM"] = 64] = "CHECKSUM";
EInspectFlags[EInspectFlags["MIME"] = 128] = "MIME";
})(EInspectFlags = exports.EInspectFlags || (exports.EInspectFlags = {}));
/**
* Status of a node operation.
*
* @export
* @enum {number}
*/
var ENodeOperationStatus;
(function (ENodeOperationStatus) {
// Node has been collected
ENodeOperationStatus[ENodeOperationStatus["COLLECTED"] = 0] = "COLLECTED";
// Node has been checked for existance
ENodeOperationStatus[ENodeOperationStatus["CHECKED"] = 1] = "CHECKED";
// Node is in progress, before copy
ENodeOperationStatus[ENodeOperationStatus["PROCESSING"] = 2] = "PROCESSING";
// Node is in process
ENodeOperationStatus[ENodeOperationStatus["PROCESS"] = 3] = "PROCESS";
// Node is in conflict, and user is being asked what to do
ENodeOperationStatus[ENodeOperationStatus["ASKING"] = 4] = "ASKING";
// Node conflict has been resolved by user
ENodeOperationStatus[ENodeOperationStatus["ANSWERED"] = 5] = "ANSWERED";
// Node has been copied
ENodeOperationStatus[ENodeOperationStatus["DONE"] = 6] = "DONE";
})(ENodeOperationStatus = exports.ENodeOperationStatus || (exports.ENodeOperationStatus = {}));
/**
* The possible modes to resolve a conflict during copy and move.
*
* @export
* @enum {number}
*/
var EResolveMode;
(function (EResolveMode) {
EResolveMode[EResolveMode["SKIP"] = 0] = "SKIP";
EResolveMode[EResolveMode["OVERWRITE"] = 1] = "OVERWRITE";
EResolveMode[EResolveMode["IF_NEWER"] = 2] = "IF_NEWER";
EResolveMode[EResolveMode["IF_SIZE_DIFFERS"] = 3] = "IF_SIZE_DIFFERS";
EResolveMode[EResolveMode["APPEND"] = 4] = "APPEND";
EResolveMode[EResolveMode["THROW"] = 5] = "THROW";
EResolveMode[EResolveMode["RETRY"] = 6] = "RETRY";
EResolveMode[EResolveMode["ABORT"] = 7] = "ABORT";
})(EResolveMode = exports.EResolveMode || (exports.EResolveMode = {}));
/**
* Additional flags for copy
*
* @export
* @enum {number}
*/
var ECopyFlags;
(function (ECopyFlags) {
/**
* Transfer atime and mtime of source to target
*/
ECopyFlags[ECopyFlags["PRESERVE_TIMES"] = 2] = "PRESERVE_TIMES";
/**
* Empty the target folder
*/
ECopyFlags[ECopyFlags["EMPTY"] = 4] = "EMPTY";
/**
* When copying, don't copy symlinks but resolve them instead.
*/
ECopyFlags[ECopyFlags["FOLLOW_SYMLINKS"] = 8] = "FOLLOW_SYMLINKS";
/**
* Collect errors & success
*/
ECopyFlags[ECopyFlags["REPORT"] = 16] = "REPORT";
})(ECopyFlags = exports.ECopyFlags || (exports.ECopyFlags = {}));
/**
* An enumeration to narrow a conflict resolve to a single item or for all following conflicts.
*
* @export
* @enum {number}
*/
var EResolve;
(function (EResolve) {
/**
* Always will use the chose conflict settings for all following conflicts.
*/
EResolve[EResolve["ALWAYS"] = 0] = "ALWAYS";
/**
* 'This' will use the conflict settings for a single conflict so the conflict callback will be triggered again for the next conflict.
*/
EResolve[EResolve["THIS"] = 1] = "THIS";
})(EResolve = exports.EResolve || (exports.EResolve = {}));
/**
* Additional flags for delete
*
* @export
* @enum {number}
*/
var EDeleteFlags;
(function (EDeleteFlags) {
EDeleteFlags[EDeleteFlags["REPORT"] = 16] = "REPORT";
})(EDeleteFlags = exports.EDeleteFlags || (exports.EDeleteFlags = {}));
//# sourceMappingURL=interfaces.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"interfaces.js","sourceRoot":"","sources":["../src/interfaces.ts"],"names":[],"mappings":";;AAAA,yDAAyD;AACzD,EAAE;AACF,SAAS;AACT,EAAE;AACF,IAAY,SAMX;AAND,WAAY,SAAS;IACpB,8BAAY,MAAM,UAAA,CAAA;IAClB,6BAAW,KAAK,SAAA,CAAA;IAChB,iCAAe,SAAS,aAAA,CAAA;IACxB,+BAAa,OAAO,WAAA,CAAA;IACpB,+BAAa,OAAO,WAAA,CAAA;AACrB,CAAC,EANW,SAAS,GAAT,iBAAS,KAAT,iBAAS,QAMpB;AAED;;;GAGG;AACQ,QAAA,MAAM,GAAQ;IACxB,IAAI,EAAE,MAAM;IACZ,MAAM,EAAE,QAAQ;IAChB,UAAU,EAAE,QAAQ;IACpB,QAAQ,EAAE,QAAQ;IAClB,YAAY,EAAE,OAAO;CACrB,CAAC;AAiDF;;;;;;;GAOG;AACH,oBAA4B,SAAQ,KAAK;CAMxC;AAND,wCAMC;AAYD;;;;;GAKG;AACH,IAAY,UAKX;AALD,WAAY,UAAU;IACrB;;OAEG;IACH,iEAAmB,CAAA;AACpB,CAAC,EALW,UAAU,GAAV,kBAAU,KAAV,kBAAU,QAKrB;AAED;;;;;GAKG;AACH,IAAY,aAQX;AARD,WAAY,aAAa;IACxB,iDAAQ,CAAA;IACR,mDAAS,CAAA;IACT,yDAAY,CAAA;IACZ,4D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,GAAZ,oBAAY,KAAZ,oBAAY,QAEvB"}

3
packages/fs/build/iterator.d.ts vendored Normal file
View File

@ -0,0 +1,3 @@
import { IProcessingNode, IBaseOptions } from './interfaces';
import { ArrayIterator } from '@plastichub/core/iterator';
export declare function async(from: string, options: IBaseOptions): Promise<ArrayIterator<IProcessingNode>>;

View File

@ -0,0 +1,53 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const tree_walker_1 = require("./utils/tree_walker");
const interfaces_1 = require("./interfaces");
const matcher_1 = require("./utils/matcher");
const iterator_1 = require("@plastichub/core/iterator");
function async(from, options) {
return __awaiter(this, void 0, void 0, function* () {
if (options && !options.filter) {
if (options.matching) {
options.filter = matcher_1.create(from, options.matching);
}
else {
options.filter = () => { return true; };
}
}
const collectorSync = function (path, item) {
if (!item) {
return;
}
if (options.filter(path)) {
nodes.push({
path: path,
item: item,
status: interfaces_1.ENodeOperationStatus.COLLECTED
});
}
};
let nodes = [];
return new Promise((resolve, reject) => {
tree_walker_1.sync(from, {
inspectOptions: {
mode: options ? options.flags & interfaces_1.EInspectFlags.MODE ? true : false : false,
times: options ? options.flags & interfaces_1.EInspectFlags.TIMES ? true : false : false,
checksum: options ? options.flags & interfaces_1.EInspectFlags.CHECKSUM ? 'md5' : null : null,
symlinks: options ? options.flags & interfaces_1.EInspectFlags.SYMLINKS ? false : true : true,
mime: options ? options.flags & interfaces_1.EInspectFlags.MIME ? true : false : false
}
}, collectorSync);
resolve(new iterator_1.ArrayIterator(nodes));
});
});
}
exports.async = async;
//# sourceMappingURL=iterator.js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K,CAAC,CAAC,CAAC,KAAK;oBACzE,KAAK,EAAE,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,KAAK,GAAG,0BAAa,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK;oBAC3E,QAAQ,EAAE,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,KAAK,GAAG,0BAAa,CAAC,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI;oBAChF,QAAQ,EAAE,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,KAAK,GAAG,0BAAa,CAAC,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI;oBAChF,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,KAAK,GAAG,0BAAa,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK;iBACzE;aACD,EAAE,aAAa,CAAC,CAAC;YAClB,OAAO,CAAC,IAAI,wBAAa,CAAkB,KAAK,CAAC,CAAC,CAAC;QACpD,CAAC,CAAC,CAAC;IACJ,CAAC;CAAA;AAjCD,sBAiCC"}

63
packages/fs/build/jetpack.d.ts vendored Normal file
View File

@ -0,0 +1,63 @@
/// <reference types="node" />
import { Options as AppendOptions } from './append';
import { IOptions as DirOptions } from './dir';
import { IOptions as FileOptions } from './file';
import { IOptions as FindOptions } from './find';
import { Options as InspectTreeOptions } from './inspect_tree';
import { IWriteOptions } from './interfaces';
import { ICopyOptions, INode, IInspectOptions } from './interfaces';
import { ReadWriteDataType, TCopyResult, ENodeType, TDeleteResult } from './interfaces';
export * from './interfaces';
export { sync, async } from './exists';
export interface IJetpack {
cwd(w?: any): IJetpack | string;
path(): string;
append(path: string, data: string | Buffer | Object, options?: AppendOptions): void;
appendAsync(path: string, data: string | Buffer | Object, options?: AppendOptions): Promise<null>;
copy(from: string, to: string, options?: ICopyOptions): void;
copyAsync(from: string, to: string, options?: ICopyOptions): Promise<TCopyResult>;
createWriteStream(path: string, options?: {
flags?: string;
encoding?: string;
fd?: number;
mode?: number;
autoClose?: boolean;
start?: number;
}): any;
createReadStream(path: string, options?: {
flags?: string;
encoding?: string;
fd?: number;
mode?: number;
autoClose?: boolean;
start?: number;
end?: number;
}): any;
dir(path: string, criteria?: DirOptions): IJetpack;
dirAsync(path: string, criteria?: DirOptions): Promise<IJetpack>;
exists(path: string): boolean | string;
existsAsync(path: string): Promise<boolean | string | ENodeType>;
file(path: string, criteria?: FileOptions): void;
fileAsync(path: string, criteria?: FileOptions): Promise<null>;
find(startPath: string, options: FindOptions): string[];
findAsync(startPath: string, options: FindOptions): Promise<string[]>;
inspect(path: string, fieldsToInclude: IInspectOptions): INode;
inspectAsync(path: string, fieldsToInclude: IInspectOptions): Promise<INode>;
inspectTree(path: string, options?: InspectTreeOptions): INode;
inspectTreeAsync(path: string, options?: InspectTreeOptions): Promise<INode>;
list(path: string): string[];
listAsync(path: string): Promise<string[]>;
move(from: string, to: string): void;
moveAsync(from: string, to: string): Promise<null>;
read(path: string, returnAs?: string): ReadWriteDataType;
readAsync(path: string, returnAs?: string): Promise<ReadWriteDataType>;
remove(path: string): void;
removeAsync(path: string): Promise<TDeleteResult>;
rename(path: string, newName: string): void;
renameAsync(path: string, newName: string): Promise<null>;
symlink(symlinkValue: string, path: string): void;
symlinkAsync(symlinkValue: string, path: string): Promise<void>;
write(path: string, data: string | Buffer | Object, options?: IWriteOptions): void;
writeAsync(path: string, data: string | Buffer | Object, options?: IWriteOptions): Promise<null>;
}
export declare const jetpack: (cwdPath?: string) => IJetpack;

View File

@ -0,0 +1,233 @@
"use strict";
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
const util = require("util");
const pathUtil = require("path");
const Q = require('q');
const append = require("./append");
const dir = require("./dir");
const file = require("./file");
const find = require("./find");
const inspect = require("./inspect");
const inspectTree = require("./inspect_tree");
const copy = require("./copy");
const exists = require("./exists");
const list = require("./list");
const move = require("./move");
const remove = require("./remove");
const rename = require("./rename");
const symlink = require("./symlink");
const streams = require("./streams");
const write = require("./write");
const read = require("./read");
__export(require("./interfaces"));
var exists_1 = require("./exists");
exports.sync = exists_1.sync;
exports.async = exists_1.async;
// The Jetpack Context object.
// It provides the public API, and resolves all paths regarding to
// passed cwdPath, or default process.cwd() if cwdPath was not specified.
exports.jetpack = (cwdPath) => {
const getCwdPath = function () {
return cwdPath || process.cwd();
};
const cwd = function (w) {
let args;
let pathParts;
// return current CWD if no arguments specified...
if (arguments.length === 0) {
return getCwdPath();
}
// ...create new CWD context otherwise
args = Array.prototype.slice.call(arguments);
pathParts = [getCwdPath()].concat(args);
const res = exports.jetpack(pathUtil.resolve.apply(null, pathParts));
return res;
};
// resolves path to inner CWD path of this jetpack instance
const resolvePath = function (path) {
return pathUtil.resolve(getCwdPath(), path);
};
const getPath = function () {
// add CWD base path as first element of arguments array
Array.prototype.unshift.call(arguments, getCwdPath());
return pathUtil.resolve.apply(null, arguments);
};
const normalizeOptions = function (options) {
return options || { cwd: getCwdPath() };
};
// API
const api = {
cwd: cwd,
path: getPath,
append: function (path, data, options) {
append.validateInput('append', path, data, options);
append.sync(resolvePath(path), data, options);
},
appendAsync: function (path, data, options) {
append.validateInput('appendAsync', path, data, options);
return append.async(resolvePath(path), data, options);
},
copy: function (from, to, options) {
copy.validateInput('copy', from, to, options);
copy.sync(resolvePath(from), resolvePath(to), options);
},
copyAsync: function (from, to, options) {
copy.validateInput('copyAsync', from, to, options);
return copy.async(resolvePath(from), resolvePath(to), options);
},
createWriteStream: function (path, options) {
return streams.createWriteStream(resolvePath(path), options);
},
createReadStream: function (path, options) {
return streams.createReadStream(resolvePath(path), options);
},
dir: function (path, criteria) {
let normalizedPath;
dir.validateInput('dir', path, criteria);
normalizedPath = resolvePath(path);
dir.sync(normalizedPath, criteria);
return cwd(normalizedPath);
},
dirAsync: function (path, criteria) {
const deferred = Q.defer();
let normalizedPath;
dir.validateInput('dirAsync', path, criteria);
normalizedPath = resolvePath(path);
dir.async(normalizedPath, criteria)
.then(function () {
deferred.resolve(cwd(normalizedPath));
}, deferred.reject);
return deferred.promise;
},
exists: function (path) {
exists.validateInput('exists', path);
return exists.sync(resolvePath(path));
},
existsAsync: function (path) {
exists.validateInput('existsAsync', path);
return exists.async(resolvePath(path));
},
file: function (path, criteria) {
file.validateInput('file', path, criteria);
file.sync(resolvePath(path), criteria);
return this;
},
fileAsync: function (path, criteria) {
const deferred = Q.defer();
const that = this;
file.validateInput('fileAsync', path, criteria);
file.async(resolvePath(path), criteria)
.then(function () {
deferred.resolve(that);
}, deferred.reject);
return deferred.promise;
},
find: function (startPath, options) {
// startPath is optional parameter, if not specified move rest of params
// to proper places and default startPath to CWD.
if (typeof options === 'undefined' && typeof startPath === 'object') {
options = startPath;
startPath = '.';
}
find.validateInput('find', startPath, options);
return find.sync(resolvePath(startPath), normalizeOptions(options));
},
findAsync: function (startPath, options) {
// startPath is optional parameter, if not specified move rest of params
// to proper places and default startPath to CWD.
if (typeof options === 'undefined' && typeof startPath === 'object') {
options = startPath;
startPath = '.';
}
find.validateInput('findAsync', startPath, options);
return find.async(resolvePath(startPath), normalizeOptions(options));
},
inspect: function (path, fieldsToInclude) {
inspect.validateInput('inspect', path, fieldsToInclude);
return inspect.sync(resolvePath(path), fieldsToInclude);
},
inspectAsync: function (path, fieldsToInclude) {
inspect.validateInput('inspectAsync', path, fieldsToInclude);
return inspect.async(resolvePath(path), fieldsToInclude);
},
inspectTree: function (path, options) {
inspectTree.validateInput('inspectTree', path, options);
return inspectTree.sync(resolvePath(path), options);
},
inspectTreeAsync: function (path, options) {
inspectTree.validateInput('inspectTreeAsync', path, options);
return inspectTree.async(resolvePath(path), options);
},
list: function (path) {
list.validateInput('list', path);
return list.sync(resolvePath(path || '.'));
},
listAsync: function (path) {
list.validateInput('listAsync', path);
return list.async(resolvePath(path || '.'));
},
move: function (from, to) {
move.validateInput('move', from, to);
move.sync(resolvePath(from), resolvePath(to));
},
moveAsync: function (from, to) {
move.validateInput('moveAsync', from, to);
return move.async(resolvePath(from), resolvePath(to));
},
read: function (path, returnAs) {
read.validateInput('read', path, returnAs);
return read.sync(resolvePath(path), returnAs);
},
readAsync: function (path, returnAs) {
read.validateInput('readAsync', path, returnAs);
return read.async(resolvePath(path), returnAs);
},
remove: function (path) {
remove.validateInput('remove', path);
// If path not specified defaults to CWD
remove.sync(resolvePath(path || '.'));
},
removeAsync: function (path) {
remove.validateInput('removeAsync', path);
// If path not specified defaults to CWD
return remove.async(resolvePath(path || '.'));
},
rename: function (path, newName) {
rename.validateInput('rename', path, newName);
rename.sync(resolvePath(path), newName);
},
renameAsync: function (path, newName) {
rename.validateInput('renameAsync', path, newName);
return rename.async(resolvePath(path), newName);
},
symlink: function (symlinkValue, path) {
symlink.validateInput('symlink', symlinkValue, path);
symlink.sync(symlinkValue, resolvePath(path));
},
symlinkAsync: function (symlinkValue, path) {
symlink.validateInput('symlinkAsync', symlinkValue, path);
return symlink.async(symlinkValue, resolvePath(path));
},
write: function (path, data, options) {
write.validateInput('write', path, data, options);
write.sync(resolvePath(path), data, options);
},
writeAsync: function (path, data, options) {
write.validateInput('writeAsync', path, data, options);
return write.async(resolvePath(path), data, options);
}
};
if (util.inspect['custom'] !== undefined) {
// Without this console.log(jetpack) throws obscure error. Details:
// https://github.com/szwacz/fs-jetpack/issues/29
// https://nodejs.org/api/util.html#util_custom_inspection_functions_on_objects
api[util.inspect['custom']] = function () {
return getCwdPath();
};
}
return api;
};
//# sourceMappingURL=jetpack.js.map

File diff suppressed because one or more lines are too long

4
packages/fs/build/list.d.ts vendored Normal file
View File

@ -0,0 +1,4 @@
export declare function validateInput(methodName: string, path: string): void;
export declare function _readdirSync(path: string): string[];
export declare function sync(path: string): string[];
export declare function async(path: string): Promise<string[]>;

72
packages/fs/build/list.js Normal file
View File

@ -0,0 +1,72 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const fs_1 = require("fs");
const validate_1 = require("./utils/validate");
const platform_1 = require("./utils/platform");
const strings_1 = require("./utils/strings");
function validateInput(methodName, path) {
const methodSignature = methodName + '(path)';
validate_1.validateArgument(methodSignature, 'path', path, ['string', 'undefined']);
}
exports.validateInput = validateInput;
;
function _readdirSync(path) {
// Mac: uses NFD unicode form on disk, but we want NFC
// See also https://github.com/nodejs/node/issues/2165
if (platform_1.isMacintosh) {
return fs_1.readdirSync(path).map(c => strings_1.normalizeNFC(c));
}
return fs_1.readdirSync(path);
}
exports._readdirSync = _readdirSync;
// ---------------------------------------------------------
// Sync
// ---------------------------------------------------------
function sync(path) {
try {
return _readdirSync(path);
}
catch (err) {
if (err.code === 'ENOENT') {
// Doesn't exist. Return undefined instead of throwing.
return undefined;
}
throw err;
}
}
exports.sync = sync;
;
// ---------------------------------------------------------
// Async
// ---------------------------------------------------------
function readdirASync(path) {
// export function readdir(path: string | Buffer, callback?: (err: NodeJS.ErrnoException, files: string[]) => void): void;
// Mac: uses NFD unicode form on disk, but we want NFC
// See also https://github.com/nodejs/node/issues/2165
return new Promise((resolve, reject) => {
if (platform_1.isMacintosh) {
fs_1.readdir(path, (err, files) => {
if (err) {
reject(err);
}
resolve(files);
});
}
fs_1.readdir(path, (err, files) => {
if (err) {
reject(err);
}
resolve(files);
});
});
}
function async(path) {
return new Promise((resolve, reject) => {
readdirASync(path)
.then((list) => resolve(list))
.catch(err => (err.code === 'ENOENT' ? resolve(undefined) : reject(err)));
});
}
exports.async = async;
;
//# sourceMappingURL=list.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"list.js","sourceRoot":"","sources":["../src/list.ts"],"names":[],"mappings":";;AAAA,2BAA0C;AAC1C,+CAAoD;AACpD,+CAA+C;AAC/C,6CAA+C;AAE/C,uBAA8B,UAAkB,EAAE,IAAY;IAC7D,MAAM,eAAe,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GAAG,CAAC,CAAC;gBACb,CAAC;gBACD,OAAO,CAAC,KAAK,CAAC,CAAC;YAChB,CAAC,CAAC,CAAC;QACJ,CAAC;QACD,YAAO,CAAC,IAAI,EAAE,CAAC,GAA0B,EAAE,KAAe,EAAE,EAAE;YAC7D,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;gBACT,MAAM,CAAC,GAAG,CAAC,CAAC;YACb,CAAC;YACD,OAAO,CAAC,KAAK,CAAC,CAAC;QAChB,CAAC,CAAC,CAAC;IACJ,CAAC,CAAC,CAAC;AACJ,CAAC;AACD,eAAsB,IAAY;IACjC,MAAM,CAAC,IAAI,OAAO,CAAW,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QAChD,YAAY,CAAC,IAAI,CAAC;aAChB,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;aAC7B,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,GAAG,CAAC,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;IAC5E,CAAC,CAAC,CAAC;AACJ,CAAC;AAND,sBAMC;AAAA,CAAC"}

3
packages/fs/build/move.d.ts vendored Normal file
View File

@ -0,0 +1,3 @@
export declare const validateInput: (methodName: string, from: string, to: string) => void;
export declare const sync: (from: string, to: string) => void;
export declare const async: (from: string, to: string) => Promise<any>;

108
packages/fs/build/move.js Normal file
View File

@ -0,0 +1,108 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const pathUtil = require("path");
const fs_1 = require("fs");
const exists_1 = require("./exists");
const validate_1 = require("./utils/validate");
const errors_1 = require("./errors");
const interfaces_1 = require("./interfaces");
const copy_1 = require("./copy");
const remove_1 = require("./remove");
const util_1 = require("util");
const dir_1 = require("./dir");
exports.validateInput = (methodName, from, to) => {
const methodSignature = methodName + '(from, to)';
validate_1.validateArgument(methodSignature, 'from', from, ['string']);
validate_1.validateArgument(methodSignature, 'to', to, ['string']);
};
// ---------------------------------------------------------
// Sync
// ---------------------------------------------------------
exports.sync = (from, to) => {
try {
fs_1.renameSync(from, to);
}
catch (err) {
// not the same device, rename doesnt work here
if (err.code === interfaces_1.EError.CROSS_DEVICE) {
try {
copy_1.sync(from, to);
}
catch (e) {
throw e;
}
try {
remove_1.sync(from);
}
catch (e) {
throw e;
}
return;
}
if (err.code !== interfaces_1.EError.NOEXISTS) {
// We can't make sense of this error. Rethrow it.
throw err;
}
else {
// Ok, source or destination path doesn't exist.
// Must do more investigation.
if (!exists_1.sync(from)) {
throw errors_1.ErrDoesntExists(from);
}
if (!exists_1.sync(to)) {
// Some parent directory doesn't exist. Create it.
dir_1.sync(pathUtil.dirname(to));
// Retry the attempt
fs_1.renameSync(from, to);
}
}
}
};
// ---------------------------------------------------------
// Async
// ---------------------------------------------------------
const ensureDestinationPathExistsAsync = (to) => {
return new Promise((resolve, reject) => {
const destDir = pathUtil.dirname(to);
exists_1.async(destDir)
.then(dstExists => {
if (!dstExists) {
dir_1.async(destDir).then(resolve, reject);
}
else {
// Hah, no idea.
reject();
}
})
.catch(reject);
});
};
exports.async = (from, to) => {
return new Promise((resolve, reject) => {
util_1.promisify(fs_1.rename)(from, to)
.then(resolve)
.catch(err => {
if (err.code !== interfaces_1.EError.NOEXISTS) {
// Something unknown. Rethrow original error.
reject(err);
}
else {
// Ok, source or destination path doesn't exist.
// Must do more investigation.
exists_1.async(from)
.then(srcExists => {
if (!srcExists) {
reject(errors_1.ErrDoesntExists(from));
}
else {
ensureDestinationPathExistsAsync(to)
.then(() => util_1.promisify(fs_1.rename)(from, to))
.then(resolve, reject);
}
})
.catch(reject);
}
});
});
};
//# sourceMappingURL=move.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"move.js","sourceRoot":"","sources":["../src/move.ts"],"names":[],"mappings":";;AAAA,iCAAkC;AAClC,2BAAwC;AACxC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AAC,WAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC;aACzB,IAAI,CAAC,OAAO,CAAC;aACb,KAAK,CAAC,GAAG,CAAC,EAAE;YACZ,EAAE,CAAC,CAAC,GAAG,CAAC,IAAI,KAAK,mBAAM,CAAC,QAAQ,CAAC,CAAC,CAAC;gBAClC,6CAA6C;gBAC7C,MAAM,CAAC,GAAG,CAAC,CAAC;YACb,CAAC;YAAC,IAAI,CAAC,CAAC;gBACP,gDAAgD;gBAChD,8BAA8B;gBAC9B,cAAW,CAAC,IAAI,CAAC;qBACf,IAAI,CAAC,SAAS,CAAC,EAAE;oBACjB,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC;wBAChB,MAAM,CAAC,wBAAe,CAAC,IAAI,CAAC,CAAC,CAAC;oBAC/B,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACP,gCAAgC,CAAC,EAAE,CAAC;6BAElC,IAAI,CAAC,GAAG,EAAE,CAAC,gBAAS,CAAC,WAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;6BACvC,IAAI,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;oBACzB,CAAC;gBACF,CAAC,CAAC;qBACD,KAAK,CAAC,MAAM,CAAC,CAAC;YACjB,CAAC;QACF,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACJ,CAAC,CAAC"}

15
packages/fs/build/promisify.d.ts vendored Normal file
View File

@ -0,0 +1,15 @@
export declare function promisify<T>(f: (cb: (err: any, res: T) => void) => void, thisContext?: any): () => Promise<T>;
export declare function promisify<A, T>(f: (arg: A, cb: (err: any, res: T) => void) => void, thisContext?: any): (arg: A) => Promise<T>;
export declare function promisify<A, A2, T>(f: (arg: A, arg2: A2, cb: (err: any, res: T) => void) => void, thisContext?: any): (arg: A, arg2: A2) => Promise<T>;
export declare function promisify<A, A2, A3, T>(f: (arg: A, arg2: A2, arg3: A3, cb: (err: any, res: T) => void) => void, thisContext?: any): (arg: A, arg2: A2, arg3: A3) => Promise<T>;
export declare function promisify<A, A2, A3, A4, T>(f: (arg: A, arg2: A2, arg3: A3, arg4: A4, cb: (err: any, res: T) => void) => void, thisContext?: any): (arg: A, arg2: A2, arg3: A3, arg4: A4) => Promise<T>;
export declare function promisify<A, A2, A3, A4, A5, T>(f: (arg: A, arg2: A2, arg3: A3, arg4: A4, arg5: A5, cb: (err: any, res: T) => void) => void, thisContext?: any): (arg: A, arg2: A2, arg3: A3, arg4: A4, arg5: A5) => Promise<T>;
export declare function map<T, U>(elts: PromiseLike<PromiseLike<T>[]>, f: (t: T) => U | PromiseLike<U>): Promise<U[]>;
export declare function map<T, U>(elts: PromiseLike<T[]>, f: (t: T) => U | PromiseLike<U>): Promise<U[]>;
export declare function map<T, U>(elts: PromiseLike<T>[], f: (t: T) => U | PromiseLike<U>): Promise<U[]>;
export declare function map<T, U>(elts: T[], f: (t: T) => U | PromiseLike<U>): Promise<U[]>;
export declare function _try<T>(f: () => T): Promise<T>;
export declare function _try<T>(f: (arg: any) => T, arg: any): Promise<T>;
export declare function _try<T>(f: (arg: any, arg2: any) => T, arg: any, arg2: any): Promise<T>;
export declare function _try<T>(f: (arg: any, arg2: any, arg3: any) => T, arg: any, arg2: any, arg3: any): Promise<T>;
export declare function _try<T>(f: (arg: any, arg2: any, arg3: any, arg4: any) => T, arg: any, arg2: any, arg3: any, arg4: any): Promise<T>;

View File

@ -0,0 +1,31 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function promisify(f, thisContext) {
return function () {
let args = Array.prototype.slice.call(arguments);
return new Promise((resolve, reject) => {
args.push((err, result) => err !== null ? reject(err) : resolve(result));
f.apply(thisContext, args);
});
};
}
exports.promisify = promisify;
function map(elts, f) {
let apply = (appElts) => Promise.all(appElts.map((elt) => typeof elt.then === 'function' ? elt.then(f) : f(elt)));
return typeof elts.then === 'function' ? elts.then(apply) : apply(elts);
}
exports.map = map;
function _try(f, thisContext) {
let args = Array.prototype.slice.call(arguments);
return new Promise((res, rej) => {
try {
args.shift();
res(f.apply(thisContext, args));
}
catch (err) {
rej(err);
}
});
}
exports._try = _try;
//# sourceMappingURL=promisify.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"promisify.js","sourceRoot":"","sources":["../src/promisify.ts"],"names":[],"mappings":";;AAOA,mBAA0B,CAAM,EAAE,WAAiB;IAClD,MAAM,CAAC;QACN,IAAI,IAAI,GAAG,KAAK,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;QACjD,MAAM,CAAC,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;YACtC,IAAI,CAAC,IAAI,CAAC,CAAC,GAAQ,EAAE,MAAW,EAAE,EAAE,CAAC,GAAG,KAAK,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC;YACnF,CAAC,CAAC,KAAK,CAAC,WAAW,EAAE,IAAI,CAAC,CAAC;QAC5B,CAAC,CAAC,CAAC;IACJ,CAAC,CAAC;AACH,CAAC;AARD,8BAQC;AAOD,aAAoB,IAAS,EAAE,CAAM;IACpC,IAAI,KAAK,GAAG,CAAC,OAAY,EAAE,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,GAAQ,EAAE,EAAE,CAAC,OAAO,GAAG,CAAC,IAAI,KAAK,UAAU,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;IAC5H,MAAM,CAAC,OAAO,IAAI,CAAC,IAAI,KAAK,UAAU,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;AACzE,CAAC;AAHD,kBAGC;AAQD,cAAqB,CAAM,EAAE,WAAiB;IAC7C,IAAI,IAAI,GAAG,KAAK,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;IACjD,MAAM,CAAC,IAAI,OAAO,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE;QAC/B,IAAI,CAAC;YACJ,IAAI,CAAC,KAAK,EAAE,CAAC;YACb,GAAG,CAAC,CAAC,CAAC,KAAK,CAAC,WAAW,EAAE,IAAI,CAAC,CAAC,CAAC;QACjC,CAAC;QAAC,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;YACd,GAAG,CAAC,GAAG,CAAC,CAAC;QACV,CAAC;IACF,CAAC,CAAC,CAAC;AACJ,CAAC;AAVD,oBAUC"}

4
packages/fs/build/read.d.ts vendored Normal file
View File

@ -0,0 +1,4 @@
import { ReadWriteDataType } from './interfaces';
export declare function validateInput(methodName: string, path: string, returnAs: string): void;
export declare function sync(path: string, returnAs?: string): ReadWriteDataType;
export declare function async(path: string, returnAs?: string): Promise<ReadWriteDataType>;

98
packages/fs/build/read.js Normal file
View File

@ -0,0 +1,98 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const fs_1 = require("fs");
const imports_1 = require("./imports");
const validate_1 = require("./utils/validate");
const Q = require('q');
const supportedReturnAs = ['utf8', 'buffer', 'json', 'jsonWithDates'];
const promisedReadFile = Q.denodeify(fs_1.readFile);
function validateInput(methodName, path, returnAs) {
const methodSignature = methodName + '(path, returnAs)';
validate_1.validateArgument(methodSignature, 'path', path, ['string']);
validate_1.validateArgument(methodSignature, 'returnAs', returnAs, ['string', 'undefined']);
if (returnAs && supportedReturnAs.indexOf(returnAs) === -1) {
throw new Error('Argument "returnAs" passed to ' + methodSignature
+ ' must have one of values: ' + supportedReturnAs.join(', '));
}
}
exports.validateInput = validateInput;
;
// Matches strings generated by Date.toJSON()
// which is called to serialize date to JSON.
const jsonDateParser = (key, value) => {
const reISO = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*))(?:Z|(\+|-)([\d|:]*))?$/;
if (typeof value === 'string') {
if (reISO.exec(value)) {
return new Date(value);
}
}
return value;
};
const ErrJson = (path, err) => {
const nicerError = new Error('JSON parsing failed while reading '
+ path + ' [' + err + ']');
nicerError.originalError = err;
return nicerError;
};
// ---------------------------------------------------------
// SYNC
// ---------------------------------------------------------
function sync(path, returnAs) {
const retAs = returnAs || 'utf8';
let data;
try {
data = fs_1.readFileSync(path, { encoding: retAs === 'buffer' ? null : 'utf8' });
}
catch (err) {
if (err.code === 'ENOENT') {
// If file doesn't exist return undefined instead of throwing.
return undefined;
}
// Otherwise rethrow the error
throw err;
}
try {
if (retAs === 'json') {
data = imports_1.json.parse(data);
}
else if (retAs === 'jsonWithDates') {
data = imports_1.json.parse(data, jsonDateParser);
}
}
catch (err) {
throw ErrJson(path, err);
}
return data;
}
exports.sync = sync;
;
// ---------------------------------------------------------
// ASYNC
// ---------------------------------------------------------
function async(path, returnAs) {
return new Promise((resolve, reject) => {
const retAs = returnAs || 'utf8';
promisedReadFile(path, { encoding: retAs === 'buffer' ? null : 'utf8' })
.then((data) => {
// Make final parsing of the data before returning.
try {
if (retAs === 'json') {
resolve(imports_1.json.parse(data));
}
else if (retAs === 'jsonWithDates') {
resolve(imports_1.json.parse(data, jsonDateParser));
}
else {
resolve(data);
}
}
catch (err) {
reject(ErrJson(path, err));
}
})
.catch((err) => (err.code === 'ENOENT' ? resolve(undefined) : reject(err)));
});
}
exports.async = async;
;
//# sourceMappingURL=read.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"read.js","sourceRoot":"","sources":["../src/read.ts"],"names":[],"mappings":";;AAAA,2BAA4C;AAE5C,uCAAiC;AACjC,+CAAoD;AAEpD,MAAM,CAAC,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC;AACvB,MAAM,iBAAiB,GAAG,CAAC,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,eAAe,CAAC,CAAC;AACtE,M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CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACrC,MAAM,KAAK,GAAG,QAAQ,IAAI,MAAM,CAAC;QACjC,gBAAgB,CAAC,IAAI,EAAE,EAAE,QAAQ,EAAE,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC;aACrE,IAAI,CAAC,CAAC,IAAuB,EAAE,EAAE;YAChC,mDAAmD;YACnD,IAAI,CAAC;gBACH,EAAE,CAAC,CAAC,KAAK,KAAK,MAAM,CAAC,CAAC,CAAC;oBACrB,OAAO,CAAC,cAAI,CAAC,KAAK,CAAC,IAAW,CAAC,CAAC,CAAC;gBACnC,CAAC;gBAAC,IAAI,CAAC,EAAE,CAAC,CAAC,KAAK,KAAK,eAAe,CAAC,CAAC,CAAC;oBACrC,OAAO,CAAC,cAAI,CAAC,KAAK,CAAC,IAAW,EAAE,cAAc,CAAC,CAAC,CAAC;gBACnD,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACN,OAAO,CAAC,IAAI,CAAC,CAAC;gBAChB,CAAC;YACH,CAAC;YAAC,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;gBACb,MAAM,CAAC,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,CAAC;YAC7B,CAAC;QACH,CAAC,CAAC;aACD,KAAK,CAAC,CAAC,GAAQ,EAAE,EAAE,CAAC,CAAC,GAAG,CAAC,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;IACrF,CAAC,CAAC,CAAC;AACL,CAAC;AApBD,sBAoBC;AAAA,CAAC"}

6
packages/fs/build/remove.d.ts vendored Normal file
View File

@ -0,0 +1,6 @@
import { IDeleteOptions } from './interfaces';
import { TDeleteResult, EResolveMode } from './interfaces';
export declare function validateInput(methodName: string, path: string): void;
export declare function sync(path: string, options?: IDeleteOptions): void;
export declare function resolveConflict(path: string, resolveMode: EResolveMode): boolean;
export declare function async(path: string, options?: IDeleteOptions): Promise<TDeleteResult>;

360
packages/fs/build/remove.js Normal file
View File

@ -0,0 +1,360 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const validate_1 = require("./utils/validate");
const inspect_1 = require("./inspect");
const list_1 = require("./list");
const pathUtil = require("path");
const fs_1 = require("fs");
const errors_1 = require("./errors");
const interfaces_1 = require("./interfaces");
const matcher_1 = require("./utils/matcher");
const interfaces_2 = require("./interfaces");
const inspect_2 = require("./inspect");
const iterator_1 = require("./iterator");
const errors_2 = require("./errors");
// tslint:disable-next-line:no-require-imports
// tslint:disable-next-line:no-var-requires
const trash = require('trash');
function validateInput(methodName, path) {
const methodSignature = methodName + '([path])';
validate_1.validateArgument(methodSignature, 'path', path, ['string', 'undefined']);
}
exports.validateInput = validateInput;
;
const parseOptions = (options, path) => {
const opts = options || {};
const parsedOptions = {};
parsedOptions.progress = opts.progress;
parsedOptions.conflictCallback = opts.conflictCallback;
parsedOptions.conflictSettings = opts.conflictSettings;
parsedOptions.debug = opts.debug;
parsedOptions.trash = opts.trash;
parsedOptions.matching = opts.matching;
if (!opts.filter) {
if (opts.matching) {
parsedOptions.filter = matcher_1.create(path, opts.matching);
}
else {
parsedOptions.filter = () => {
return true;
};
}
}
return parsedOptions;
};
// ---------------------------------------------------------
// Sync
// ---------------------------------------------------------
function sync(path, options) {
const inspectedFile = inspect_1.sync(path, { symlinks: true });
if (inspectedFile === undefined) {
// The path already doesn't exits. Nothing to do here.
}
else if (inspectedFile.type === 'dir') {
list_1.sync(path).forEach((filename) => {
sync(pathUtil.join(path, filename));
});
fs_1.rmdirSync(path);
}
else if (inspectedFile.type === 'file' || inspectedFile.type === 'symlink') {
fs_1.unlinkSync(path);
}
else {
throw errors_1.ErrNoFileOrDir(path);
}
}
exports.sync = sync;
;
const rmTrash = (path) => {
return trash([path]);
};
// ---------------------------------------------------------
// Async
// ---------------------------------------------------------
const rmASync = (path, options) => {
return options.trash ? rmTrash(path) : new Promise((resolve, reject) => {
fs_1.unlink(path, (err) => {
if (!err) {
resolve();
}
else {
reject(err);
}
});
});
};
const isDone = (nodes) => {
let done = true;
nodes.forEach((element) => {
if (element.status !== interfaces_2.ENodeOperationStatus.DONE) {
done = false;
}
});
return done;
};
const next = (nodes) => {
for (let i = 0; i < nodes.length; i++) {
if (nodes[i].status === interfaces_2.ENodeOperationStatus.COLLECTED) {
return nodes[i];
}
}
return null;
};
// handle user side setting "THROW" and non enum values (null)
const onConflict = (from, options, settings) => {
switch (settings.overwrite) {
case interfaces_2.EResolveMode.THROW: {
throw errors_2.ErrCantDelete(from);
}
case interfaces_2.EResolveMode.OVERWRITE:
case interfaces_2.EResolveMode.APPEND:
case interfaces_2.EResolveMode.IF_NEWER:
case interfaces_2.EResolveMode.ABORT:
case interfaces_2.EResolveMode.IF_SIZE_DIFFERS:
case interfaces_2.EResolveMode.SKIP: {
return settings.overwrite;
}
default: {
return undefined;
}
}
};
function resolveConflict(path, resolveMode) {
if (resolveMode === undefined) {
return true;
}
if (resolveMode === interfaces_2.EResolveMode.SKIP) {
return false;
}
else if (resolveMode === interfaces_2.EResolveMode.ABORT) {
return false;
}
else if (resolveMode === interfaces_2.EResolveMode.RETRY) {
return true;
}
return false;
}
exports.resolveConflict = resolveConflict;
;
const visitor = (path, vars, item) => {
const options = vars.options;
if (!item) {
return;
}
item.status = interfaces_2.ENodeOperationStatus.PROCESSING;
const done = () => {
item.status = interfaces_2.ENodeOperationStatus.DONE;
if (isDone(vars.nodes)) {
return vars.resolve(vars.result);
}
else {
if (vars.nodes.length) {
const itemInner = next(vars.nodes);
if (itemInner) {
visitor(itemInner.path, vars, itemInner);
}
else {
vars.resolve(vars.result);
}
}
}
};
if (isDone(vars.nodes)) {
return vars.resolve(vars.result);
}
vars.filesInProgress += 1;
rmASync(path, options)
.then((res) => {
done();
})
.catch((err) => {
if (err.code === 'EACCES' || err.code === 'EPERM' || err.code === 'EISDIR' || err.code === 'ENOTEMPTY') {
const resolved = (settings) => {
settings.error = err.code;
// feature : report
if (settings && options && options.flags && options.flags & interfaces_2.EDeleteFlags.REPORT) {
vars.result.push({
error: settings.error,
node: item,
resolved: settings
});
}
if (settings) {
// if the first resolve callback returned an individual resolve settings "THIS",
// ask the user again with the same item
const always = settings.mode === interfaces_2.EResolve.ALWAYS;
if (always) {
options.conflictSettings = settings;
}
let how = settings.overwrite;
how = onConflict(item.path, options, settings);
if (how === interfaces_2.EResolveMode.ABORT) {
vars.abort = true;
}
if (vars.abort) {
done();
return;
}
if (!resolveConflict(item.path, how)) {
done();
return;
}
item.status = interfaces_2.ENodeOperationStatus.PROCESS;
if (settings.overwrite === interfaces_2.EResolveMode.RETRY) {
item.status = interfaces_2.ENodeOperationStatus.COLLECTED;
visitor(path, vars, item);
}
}
};
if (!options.conflictSettings) {
const promise = options.conflictCallback(path, inspect_2.createItem(path), err.code);
promise.then(resolved);
}
else {
resolved(options.conflictSettings);
}
}
});
};
function collect(path, options) {
return __awaiter(this, void 0, void 0, function* () {
return new Promise((resolve, reject) => {
const all = [];
iterator_1.async(path, {
filter: options.filter
}).then((it) => {
let node = null;
while (node = it.next()) {
all.push({
path: node.path,
item: node.item,
status: interfaces_2.ENodeOperationStatus.COLLECTED
});
}
resolve(all);
}).catch((err) => {
console.error('read error', err);
});
});
});
}
function async(path, options) {
return __awaiter(this, void 0, void 0, function* () {
options = parseOptions(options, path);
const onError = (err, resolve, reject, nodes) => {
if (err.code === 'EPERM' || err.code === 'EISDIR' || err.code === 'ENOTEMPTY') {
const proceed = () => {
// It's not a file, it's a directory.
// Must delete everything inside first.
list_1.async(path).then((filenamesInsideDir) => {
const promises = filenamesInsideDir.map((filename) => {
return async(pathUtil.join(path, filename), options);
});
return Promise.all(promises);
}).then(() => {
// Everything inside directory has been removed,
// it's safe now to go for the directory itself.
return fs_1.rmdir(path, (err2) => {
if (err2) {
reject(err2);
}
});
})
.then(resolve, reject);
};
// we have a user conflict callback,
// collect nodes and start asking
if (options.conflictCallback) {
const result = void 0;
// walker variables
const visitorArgs = {
resolve: resolve,
reject: reject,
abort: false,
filesInProgress: 0,
resolveSettings: null,
options: options,
result: result,
nodes: nodes || []
};
const process = () => {
visitorArgs.nodes = nodes;
if (isDone(nodes)) {
return resolve(result);
}
if (nodes.length) {
const item = next(nodes);
if (item) {
visitor(item.path, visitorArgs, item);
}
}
};
if (!nodes) {
const _nodes = visitorArgs.nodes;
iterator_1.async(path, {
filter: options.filter
}).then((it) => {
let node = null;
while (node = it.next()) {
_nodes.push({
path: node.path,
item: node.item,
status: interfaces_2.ENodeOperationStatus.COLLECTED
});
}
process();
}).catch((err2) => {
console.error('read error', err2);
});
}
else {
process();
}
}
else {
proceed();
}
}
else if (err.code === 'ENOENT') {
// File already doesn't exist. We're done.
resolve();
}
else {
// Something unexpected happened. Rethrow original error.
reject(err);
}
};
// if matching is set, its like rm somePath/*.ext
// in this case, we collect the inner matching nodes and proceed as it
// would be an error
if (options.matching) {
const nodes = yield collect(path, options);
const err = new interfaces_1.ErrnoException('dummy');
err.code = 'ENOTEMPTY';
return new Promise((resolve, reject) => {
onError(err, resolve, reject, nodes);
});
}
else {
return new Promise((resolve, reject) => {
// Assume the path is a file or directory and just try to remove it.
rmASync(path, options)
.then((res) => resolve())
.catch((err) => {
onError(err, resolve, reject);
});
});
}
});
}
exports.async = async;
;
//# sourceMappingURL=remove.js.map

File diff suppressed because one or more lines are too long

3
packages/fs/build/rename.d.ts vendored Normal file
View File

@ -0,0 +1,3 @@
export declare function validateInput(methodName: string, path: string, newName: string): void;
export declare function sync(path: string, newName: string): void;
export declare function async(path: string, newName: string): Promise<null>;

View File

@ -0,0 +1,27 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const pathUtil = require("path");
const move_1 = require("./move");
const validate_1 = require("./utils/validate");
function validateInput(methodName, path, newName) {
const methodSignature = methodName + '(path, newName)';
validate_1.validateArgument(methodSignature, 'path', path, ['string']);
validate_1.validateArgument(methodSignature, 'newName', newName, ['string']);
}
exports.validateInput = validateInput;
;
// ---------------------------------------------------------
// Sync
// ---------------------------------------------------------
function sync(path, newName) {
move_1.sync(path, pathUtil.join(pathUtil.dirname(path), newName));
}
exports.sync = sync;
// ---------------------------------------------------------
// Async
// ---------------------------------------------------------
function async(path, newName) {
return move_1.async(path, pathUtil.join(pathUtil.dirname(path), newName));
}
exports.async = async;
//# sourceMappingURL=rename.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"rename.js","sourceRoot":"","sources":["../src/rename.ts"],"names":[],"mappings":";;AAAA,iCAAiC;AACjC,iCAA8D;AAC9D,+CAAoD;AAEpD,uBAA8B,UAAkB,EAAE,IAAY,EAAE,OAAe;IAC7E,MAAM,eAAe,GAAG,UAAU,GAAG,iBAAiB,CAAC;IACvD,2BAAgB,CAAC,eAAe,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,QAAQ,CAAC,CAAC,CAAC;IAC5D,2BAAgB,CAAC,eAAe,EAAE,SAAS,EAAE,OAAO,EAAE,CAAC,QAAQ,CAAC,CAAC,CAAC;AACpE,CAAC;AAJD,sCAIC;AAAA,CAAC;AAEF,4DAA4D;AAC5D,OAAO;AACP,4DAA4D;AAC5D,cAAqB,IAAY,EAAE,OAAe;IAChD,WAAQ,CAAC,IAAI,EAAE,QAAQ,CAAC,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC;AACjE,CAAC;AAFD,oBAEC;AAED,4DAA4D;AAC5D,QAAQ;AACR,4DAA4D;AAC5D,eAAsB,IAAY,EAAE,OAAe;IACjD,MAAM,CAAC,YAAS,CAAC,IAAI,EAAE,QAAQ,CAAC,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC;AACzE,CAAC;AAFD,sBAEC"}

2
packages/fs/build/streams.d.ts vendored Normal file
View File

@ -0,0 +1,2 @@
export { createWriteStream } from 'fs';
export { createReadStream } from 'fs';

View File

@ -0,0 +1,7 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var fs_1 = require("fs");
exports.createWriteStream = fs_1.createWriteStream;
var fs_2 = require("fs");
exports.createReadStream = fs_2.createReadStream;
//# sourceMappingURL=streams.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"streams.js","sourceRoot":"","sources":["../src/streams.ts"],"names":[],"mappings":";;AAAA,yBAAqC;AAA7B,iCAAA,iBAAiB,CAAA;AACzB,yBAAoC;AAA5B,gCAAA,gBAAgB,CAAA"}

3
packages/fs/build/symlink.d.ts vendored Normal file
View File

@ -0,0 +1,3 @@
export declare function validateInput(methodName: string, symlinkValue: string, path: string): void;
export declare function sync(symlinkValue: string, path: string): void;
export declare function async(symlinkValue: string, path: string): Promise<void>;

View File

@ -0,0 +1,57 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const Q = require('q');
const fs = require("fs");
const mkdirp = require("mkdirp");
const pathUtil = require("path");
const validate_1 = require("./utils/validate");
const promisedSymlink = Q.denodeify(fs.symlink);
const promisedMkdirp = Q.denodeify(mkdirp);
function validateInput(methodName, symlinkValue, path) {
const methodSignature = methodName + '(symlinkValue, path)';
validate_1.validateArgument(methodSignature, 'symlinkValue', symlinkValue, ['string']);
validate_1.validateArgument(methodSignature, 'path', path, ['string']);
}
exports.validateInput = validateInput;
;
// ---------------------------------------------------------
// Sync
// ---------------------------------------------------------
function sync(symlinkValue, path) {
try {
fs.symlinkSync(symlinkValue, path);
}
catch (err) {
if (err.code === 'ENOENT') {
// Parent directories don't exist. Just create them and rety.
mkdirp.sync(pathUtil.dirname(path));
fs.symlinkSync(symlinkValue, path);
}
else {
throw err;
}
}
}
exports.sync = sync;
// ---------------------------------------------------------
// Async
// ---------------------------------------------------------
function async(symlinkValue, path) {
return new Promise((resolve, reject) => {
promisedSymlink(symlinkValue, path)
.then(resolve)
.catch((err) => {
if (err.code === 'ENOENT') {
// Parent directories don't exist. Just create them and rety.
promisedMkdirp(pathUtil.dirname(path))
.then(() => { return promisedSymlink(symlinkValue, path); })
.then(resolve, reject);
}
else {
reject(err);
}
});
});
}
exports.async = async;
//# sourceMappingURL=symlink.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"symlink.js","sourceRoot":"","sources":["../src/symlink.ts"],"names":[],"mappings":";;AAAA,MAAM,CAAC,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC;AACvB,yBAAyB;AACzB,iCAAiC;AACjC,iCAAkC;AAClC,+CAAoD;AACpD,MAAM,eAAe,GAAG,CAAC,CAAC,SAAS,CAAC,EAAE,CAAC,OAAO,CAAC,CAAC;AAChD,MAAM,cAAc,GAAG,CAAC,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC;AAE3C,uBAA8B,UAAkB,EAAE,YAAoB,EAAE,IAAY;IAClF,MAAM,eAAe,GAAG,UAAU,GAAG,sBAAsB,CAAC;IAC5D,2BAAgB,CAAC,eAAe,EAAE,cAAc,EAAE,YAAY,EAAE,CAAC,QAAQ,CAAC,CAAC,CAAC;IAC5E,2BAAgB,CAAC,eAAe,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,QAAQ,CAAC,CAAC,CAAC;AAC9D,CAAC;AAJD,sCAIC;AAAA,CAAC;AACF,4DAA4D;AAC5D,OAAO;AACP,4DAA4D;AAE5D,cAAqB,YAAoB,EAAE,IAAY;IACrD,IAAI,CAAC;QACH,EAAE,CAAC,WAAW,CAAC,YAAY,EAAE,IAAI,CAAC,CAAC;IACrC,CAAC;IAAC,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;QACb,EAAE,CAAC,CAAC,GAAG,CAAC,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC;YAC1B,6DAA6D;YAC7D,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC;YACpC,EAAE,CAAC,WAAW,CAAC,YAAY,EAAE,IAAI,CAAC,CAAC;QACrC,CAAC;QAAC,IAAI,CAAC,CAAC;YACN,MAAM,GAAG,CAAC;QACZ,CAAC;IACH,CAAC;AACH,CAAC;AAZD,oBAYC;AAED,4DAA4D;AAC5D,QAAQ;AACR,4DAA4D;AAC5D,eAAsB,YAAoB,EAAE,IAAY;IACtD,MAAM,CAAC,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACrC,eAAe,CAAC,YAAY,EAAE,IAAI,CAAC;aAChC,IAAI,CAAC,OAAO,CAAC;aACb,KAAK,CAAC,CAAC,GAAQ,EAAE,EAAE;YAClB,EAAE,CAAC,CAAC,GAAG,CAAC,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC;gBAC1B,6DAA6D;gBAC7D,cAAc,CAAC,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;qBACnC,IAAI,CAAC,GAAG,EAAE,GAAG,MAAM,CAAC,eAAe,CAAC,YAAY,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;qBAC3D,IAAI,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;YAC3B,CAAC;YAAC,IAAI,CAAC,CAAC;gBACN,MAAM,CAAC,GAAG,CAAC,CAAC;YACd,CAAC;QACH,CAAC,CAAC,CAAC;IACP,CAAC,CAAC,CAAC;AACL,CAAC;AAfD,sBAeC"}

6
packages/fs/build/utils/matcher.d.ts vendored Normal file
View File

@ -0,0 +1,6 @@
export interface IOptions {
matchBase: boolean;
nocomment: boolean;
dot: boolean;
}
export declare function create(basePath: string, patterns: string[], options?: IOptions): (absolutePath: string) => boolean;

View File

@ -0,0 +1,70 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const minimatch_1 = require("minimatch");
const patternToAbsolutePath = (basePath, pattern) => {
// All patterns without slash are left as they are, if pattern contain
// any slash we need to turn it into absolute path.
const hasSlash = (pattern.indexOf('/') !== -1);
const isAbsolute = /^!?\//.test(pattern);
const isNegated = /^!/.test(pattern);
let separator;
if (!isAbsolute && hasSlash) {
// Throw out meaningful characters from the beginning ("!", "./").
pattern = pattern.replace(/^!/, '').replace(/^\.\//, '');
if (/\/$/.test(basePath)) {
separator = '';
}
else {
separator = '/';
}
if (isNegated) {
return '!' + basePath + separator + pattern;
}
return basePath + separator + pattern;
}
return pattern;
};
function create(basePath, patterns, options) {
let matchers;
if (typeof patterns === 'string') {
patterns = [patterns];
}
matchers = patterns.map(pattern => {
return patternToAbsolutePath(basePath, pattern);
}).map(pattern => {
return new minimatch_1.Minimatch(pattern, options || {
matchBase: true,
nocomment: true,
dot: true
});
});
return function performMatch(absolutePath) {
let mode = 'matching';
let weHaveMatch = false;
let currentMatcher;
let i;
for (i = 0; i < matchers.length; i += 1) {
currentMatcher = matchers[i];
if (currentMatcher.negate) {
mode = 'negation';
if (i === 0) {
// There are only negated patterns in the set,
// so make everything matching by default and
// start to reject stuff.
weHaveMatch = true;
}
}
if (mode === 'negation' && weHaveMatch && !currentMatcher.match(absolutePath)) {
// One negation match is enought to know we can reject this one.
return false;
}
if (mode === 'matching' && !weHaveMatch) {
weHaveMatch = currentMatcher.match(absolutePath);
}
}
return weHaveMatch;
};
}
exports.create = create;
;
//# sourceMappingURL=matcher.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"matcher.js","sourceRoot":"","sources":["../../src/utils/matcher.ts"],"names":[],"mappings":";;AAAA,yCAAsC;AAMtC,MAAM,qBAAqB,GAAG,CAAC,QAAgB,EAAE,OAAe,EAAU,EAAE;IAC3E,sEAAsE;IACtE,mDAAmD;IACnD,MAAM,QA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0 +1 @@
export declare const normalizeFileMode: (mode: string | number) => string;

View File

@ -0,0 +1,14 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
// Converts mode to string 3 characters long.
exports.normalizeFileMode = (mode) => {
let modeAsString;
if (typeof mode === 'number') {
modeAsString = mode.toString(8);
}
else {
modeAsString = mode;
}
return modeAsString.substring(modeAsString.length - 3);
};
//# sourceMappingURL=mode.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"mode.js","sourceRoot":"","sources":["../../src/utils/mode.ts"],"names":[],"mappings":";;AAAA,6CAA6C;AAChC,QAAA,iBAAiB,GAAG,CAAC,IAAqB,EAAU,EAAE;IAClE,IAAI,YAAoB,CAAC;IACzB,EAAE,CAAC,CAAC,OAAO,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC;QAC9B,YAAY,GAAG,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC;IACjC,CAAC;IAAC,IAAI,CAAC,CAAC;QACP,YAAY,GAAG,IAAI,CAAC;IACrB,CAAC;IACD,MAAM,CAAC,YAAY,CAAC,SAAS,CAAC,YAAY,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;AACxD,CAAC,CAAC"}

15
packages/fs/build/utils/platform.d.ts vendored Normal file
View File

@ -0,0 +1,15 @@
export declare enum Platform {
Web = 0,
Mac = 1,
Linux = 2,
Windows = 3,
}
export declare let _platform: Platform;
export declare const isWindows: boolean;
export declare const isMacintosh: boolean;
export declare const isLinux: boolean;
export declare const isRootUser: boolean;
export declare const isNative: boolean;
export declare const isWeb: boolean;
export declare const isQunit: boolean;
export declare const platform: Platform;

View File

@ -0,0 +1,45 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var Platform;
(function (Platform) {
Platform[Platform["Web"] = 0] = "Web";
Platform[Platform["Mac"] = 1] = "Mac";
Platform[Platform["Linux"] = 2] = "Linux";
Platform[Platform["Windows"] = 3] = "Windows";
})(Platform = exports.Platform || (exports.Platform = {}));
let _isWindows = false;
let _isMacintosh = false;
let _isLinux = false;
let _isRootUser = false;
let _isNative = false;
let _isWeb = false;
let _isQunit = false;
exports._platform = Platform.Web;
// OS detection
if (typeof process === 'object') {
_isWindows = (process.platform === 'win32');
_isMacintosh = (process.platform === 'darwin');
_isLinux = (process.platform === 'linux');
_isRootUser = !_isWindows && (process.getuid() === 0);
_isNative = true;
}
if (_isNative) {
if (_isMacintosh) {
exports._platform = Platform.Mac;
}
else if (_isWindows) {
exports._platform = Platform.Windows;
}
else if (_isLinux) {
exports._platform = Platform.Linux;
}
}
exports.isWindows = _isWindows;
exports.isMacintosh = _isMacintosh;
exports.isLinux = _isLinux;
exports.isRootUser = _isRootUser;
exports.isNative = _isNative;
exports.isWeb = _isWeb;
exports.isQunit = _isQunit;
exports.platform = exports._platform;
//# sourceMappingURL=platform.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"platform.js","sourceRoot":"","sources":["../../src/utils/platform.ts"],"names":[],"mappings":";;AAAA,IAAY,QAKX;AALD,WAAY,QAAQ;IACnB,qCAAG,CAAA;IACH,qCAAG,CAAA;IACH,yCAAK,CAAA;IACL,6CAAO,CAAA;AACR,CAAC,EALW,QAAQ,GAAR,gBAAQ,KAAR,gBAAQ,QAKnB;AACD,IAAI,UAAU,GAAG,KAAK,CAAC;AACvB,IAAI,YAAY,GAAG,KAAK,CAAC;AACzB,IAAI,QAAQ,GAAG,KAAK,CAAC;AACrB,IAAI,WAAW,GAAG,KAAK,CAAC;AACxB,IAAI,SAAS,GAAG,KAAK,CAAC;AACtB,IAAI,MAAM,GAAG,KAAK,CAAC;AACnB,IAAI,QAAQ,GAAG,KAAK,CAAC;AACV,QAAA,SAAS,GAAa,QAAQ,CAAC,GAAG,CAAC;AAC9C,eAAe;AACf,EAAE,CAAC,CAAC,OAAO,OAAO,KAAK,QAAQ,CAAC,CAAC,CAAC;IACjC,UAAU,GAAG,CAAC,OAAO,CAAC,QAAQ,KAAK,OAAO,CAAC,CAAC;IAC5C,YAAY,GAAG,CAAC,OAAO,CAAC,QAAQ,KAAK,QAAQ,CAAC,CAAC;IAC/C,QAAQ,GAAG,CAAC,OAAO,CAAC,QAAQ,KAAK,OAAO,CAAC,CAAC;IAC1C,WAAW,GAAG,CAAC,UAAU,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC,CAAC;IACtD,SAAS,GAAG,IAAI,CAAC;AAClB,CAAC;AACD,EAAE,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC;IACf,EAAE,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC;QAClB,iBAAS,GAAG,QAAQ,CAAC,GAAG,CAAC;IAC1B,CAAC;IAAC,IAAI,CAAC,EAAE,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC;QACvB,iBAAS,GAAG,QAAQ,CAAC,OAAO,CAAC;IAC9B,CAAC;IAAC,IAAI,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC;QACrB,iBAAS,GAAG,QAAQ,CAAC,KAAK,CAAC;IAC5B,CAAC;AACF,CAAC;AAEY,QAAA,SAAS,GAAG,UAAU,CAAC;AACvB,QAAA,WAAW,GAAG,YAAY,CAAC;AAC3B,QAAA,OAAO,GAAG,QAAQ,CAAC;AACnB,QAAA,UAAU,GAAG,WAAW,CAAC;AACzB,QAAA,QAAQ,GAAG,SAAS,CAAC;AACrB,QAAA,KAAK,GAAG,MAAM,CAAC;AACf,QAAA,OAAO,GAAG,QAAQ,CAAC;AACnB,QAAA,QAAQ,GAAG,iBAAS,CAAC"}

2
packages/fs/build/utils/strings.d.ts vendored Normal file
View File

@ -0,0 +1,2 @@
export declare let canNormalize: boolean;
export declare const normalizeNFC: (str: string) => string;

View File

@ -0,0 +1,18 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.canNormalize = typeof (''.normalize) === 'function';
const nonAsciiCharactersPattern = /[^\u0000-\u0080]/;
exports.normalizeNFC = (str) => {
if (!exports.canNormalize || !str) {
return str;
}
let res;
if (nonAsciiCharactersPattern.test(str)) {
res = str.normalize('NFC');
}
else {
res = str;
}
return res;
};
//# sourceMappingURL=strings.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"strings.js","sourceRoot":"","sources":["../../src/utils/strings.ts"],"names":[],"mappings":";;AAAW,QAAA,YAAY,GAAG,OAAO,CAAQ,EAAG,CAAC,SAAS,CAAC,KAAK,UAAU,CAAC;AACvE,MAAM,yBAAyB,GAAG,kBAAkB,CAAC;AACxC,QAAA,YAAY,GAAG,CAAC,GAAW,EAAU,EAAE;IACnD,EAAE,CAAC,CAAC,CAAC,oBAAY,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;QAC3B,MAAM,CAAC,GAAG,CAAC;IACZ,CAAC;IAED,IAAI,GAAW,CAAC;IAChB,EAAE,CAAC,CAAC,yBAAyB,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;QACzC,GAAG,GAAU,GAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;IACpC,CAAC;IAAC,IAAI,CAAC,CAAC;QACP,GAAG,GAAG,GAAG,CAAC;IACX,CAAC;IACD,MAAM,CAAC,GAAG,CAAC;AACZ,CAAC,CAAA"}

View File

@ -0,0 +1,10 @@
/// <reference types="node" />
import { Readable } from 'stream';
import { IInspectOptions, INode } from '../interfaces';
export interface IOptions {
inspectOptions: IInspectOptions;
maxLevelsDeep?: number;
user?: any;
}
export declare function sync(path: string, options: IOptions, callback: (path: string, item: INode) => void, currentLevel?: number): void;
export declare function stream(path: string, options: IOptions): Readable;

Some files were not shown because too many files have changed in this diff Show More