Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Move config to an external file #32

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 16 additions & 19 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,26 +9,14 @@ _Installs dependencies from a local checkout, and keeps them in sync, without th

# Summary

Relative deps introduces an additional dependency section in `package.json`, called `relativeDependencies`.
This section contains paths to the local sources of any dependency, that will be built and installed over the publicly available versions, when needed.
Relative deps introduces an additional dependency config file called `.relativeDependenciesrc`
This config contains paths to the local sources of any dependency, that will be built and installed over the publicly available versions, when needed.

Example `package.json`:
Example `relativeDependenciesrc`:

```json
{
"name": "my-project",
"dependencies": {
"my-cool-library": "0.1.0"
},
"relativeDependencies": {
"my-cool-library": "../../packages/my-cool-library"
},
"scripts": {
"prepare": "relative-deps"
},
"devDependencies": {
"relative-deps": "^1.0.0"
}
"my-cool-library": "../../packages/my-cool-library"
dvh91 marked this conversation as resolved.
Show resolved Hide resolved
}
```

Expand Down Expand Up @@ -72,15 +60,14 @@ Options:

Alias `-S`. Default: `prepare`. Script name which is using for running `relative-deps`.

Running this script will install `relative-deps`, add script and initialize empty `relativeDependencies` section.
Running this script will install `relative-deps`, add `prepare` script and create an empty `.relativeDependenciesrc` file.

```json
{
"name": "my-project",
"devDependencies": {
"relative-deps": "^1.0.0"
},
"relativeDependencies": {},
"scripts": {
"prepare": "relative-deps"
}
Expand All @@ -103,6 +90,16 @@ Optionally, you can add this step also for more scripts, for example before star

In general, this doesn't add to much overhead, since usually relative-deps is able to determine rather quickly (~0.5 sec) that there are no changes.

### Configuration alternatives

We use [`cosmiconfig`](https://github.com/davidtheclark/cosmiconfig) to load the config for this library so you could configure `relative-deps` in few ways, depends on your prefference:

- a `relativeDependencies` property in package.json
- a `.relativeDependenciesrc` file in JSON or YAML format
- a `.relativeDependenciesrc.json` file
- a `.relativeDependenciesrc.yaml`, `.relativeDependenciesrc.yml`, or `.relativeDependenciesrc.js` file
- a ``relativeDependencies.config.js`` file exporting a JS object

## Adding a relative dependency

Running following script will initialize `relative-deps` if not initialized yet, find the package at the provided path, install it as normal dependency and pack relative-dependency.
Expand Down Expand Up @@ -150,7 +147,7 @@ Roughly, it works like this (obviously this can get out of date quickly):

```
- pre: yarn.lock exists or die
- read relativeDeps from nearest package.json
- read relativeDeps from nearest config file (or from `package.json` relativeDependencies section)
- doesn't exist? warn & exit
- for each relativeDep:
- check if target path exists
Expand Down
76 changes: 59 additions & 17 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,15 @@ const globby = require("globby")
const checksum = require("checksum")
const merge = require("lodash/merge")
const { spawn } = require("yarn-or-npm")
const { cosmiconfigSync } = require('cosmiconfig')
const configExplorer = cosmiconfigSync('relativeDependencies', { ignoreEmptySearchPlaces: false });

async function installRelativeDeps() {
const projectPkgJson = readPkgUp.sync()

const relativeDependencies = projectPkgJson.package.relativeDependencies
const { config: relativeDependencies } = getConfig()

if (!relativeDependencies) {
console.warn("[relative-deps][WARN] No 'relativeDependencies' specified in package.json")
console.warn("[relative-deps][WARN] No 'relativeDependencies' configuration found")
process.exit(0)
}

Expand Down Expand Up @@ -185,24 +186,20 @@ function addScriptToPackage(script) {
}

function installRelativeDepsPackage() {
let pkg = getPackageJson()
let { config } = getConfig();

if (!(
(pkg.devDependencies && pkg.devDependencies["relative-deps"]) ||
(pkg.dependencies && pkg.dependencies["relative-deps"])
)) {
if (config) {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think this condition is not correct, the goal of this step here is to install relative-deps itself to the package if not yet present. Probably should be !config?

console.log('[relative-deps] Installing relative-deps package')
spawn.sync(["add -D relative-deps"])
}
}

function setupEmptyRelativeDeps () {
let pkg = getPackageJson()
let { config } = getConfig()

if (!pkg.relativeDependencies) {
console.log(`[relative-deps] Setting up relativeDependencies section in package.json`)
pkg.relativeDependencies = {}
setPackageData(pkg)
if (!config) {
console.log(`[relative-deps] Setting up relativeDependencies config file`)
setConfig({})
}
}

Expand All @@ -213,7 +210,6 @@ function initRelativeDeps({ script }) {
}

async function addRelativeDeps({ paths, dev, script }) {
initRelativeDeps({ script })

if (!paths || paths.length === 0) {
console.log(`[relative-deps][WARN] no paths provided running ${script}`)
Expand All @@ -239,6 +235,24 @@ async function addRelativeDeps({ paths, dev, script }) {
})

let pkg = getPackageJson()
let { config, filepath } = getConfig()

if (!filepath) {
console.error(
`[relative-deps][ERROR] You havn't initilized relative-deps yet. run "npx relative-deps init" and try again.`
)
process.exit(1);
}

// the other file formats will require complex parsing and it's not in the scope of work.
const allowedConfigFiles = ['package.json', 'relativeDependenciesrc', 'relativeDependenciesrc.json'];
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks like this block (248 - 255) of loading and validation config should be a function that is used wherever config is loaded, so for example at line 15 as well?


if (!allowedConfigFiles.some(allowedConfig => filepath.endsWith(allowedConfig))) {
console.error(
`[relative-deps][ERROR] We don't support adding new relative dependencies in your chosen config file. you can add them manually.`
)
process.exit(1);
}

const depsKey = dev ? "devDependencies" : "dependencies"
if (!pkg[depsKey]) pkg[depsKey] = {}
Expand All @@ -253,13 +267,12 @@ async function addRelativeDeps({ paths, dev, script }) {
}
})

if (!pkg.relativeDependencies) pkg.relativeDependencies = {}

libraries.forEach(dependency => {
pkg.relativeDependencies[dependency.name] = dependency.relPath
config[dependency.name] = dependency.relPath
})

setPackageData(pkg)
setConfig(config)
await installRelativeDeps()
}

Expand All @@ -271,10 +284,39 @@ function setPackageData(pkgData) {
)
}

function setConfig(config) {
let { filepath } = getConfig();

if (!filepath) {
filepath = path.join(process.cwd(), ".relativeDependenciesrc")
}

if (filepath.includes('package.json')) {
const packageJson = getPackageJson();
packageJson.relativeDependencies = config;

fs.writeFileSync(
filepath,
JSON.stringify(packageJson, null, 2)
)
return;
}

fs.writeFileSync(
filepath,
JSON.stringify(config, null, 2)
)

}

function getPackageJson() {
return JSON.parse(fs.readFileSync(path.join(process.cwd(), 'package.json'), "utf-8"))
}

function getConfig() {
return configExplorer.search() || { config: null, filepath: null };
}

module.exports.installRelativeDeps = installRelativeDeps
module.exports.initRelativeDeps = initRelativeDeps
module.exports.addRelativeDeps = addRelativeDeps
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
"homepage": "https://github.com/mweststrate/relative-deps#readme",
"dependencies": {
"checksum": "^0.1.1",
"cosmiconfig": "^6.0.0",
"globby": "^9.2.0",
"lodash": "^4.17.15",
"read-pkg-up": "^6.0.0",
Expand Down
Loading