Skip to content

Commit

Permalink
implement #1808, support adding dist-path-template as a package-json …
Browse files Browse the repository at this point in the history
…value, which gets replaced with the calculated dist path upon import (#1823)
  • Loading branch information
davidfirst authored Jul 13, 2019
1 parent 3c4e098 commit b087476
Show file tree
Hide file tree
Showing 7 changed files with 79 additions and 17 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/).

## [unreleased]

- [#1808](https://github.com/teambit/bit/issues/1808) support adding dist-path-template as a package-json value, which gets replaced with the calculated dist path upon import
- update execa to v2.0.3
- [#1792](https://github.com/teambit/bit/issues/1792) don't generate entry-point files for nested dependencies when their `package.json` is written
- [#1817](https://github.com/teambit/bit/issues/1817) fix ComponentNotFound error when tagging after export & tag & untag for author using compiler that builds dependencies
Expand Down
19 changes: 18 additions & 1 deletion e2e/commands/build.e2e.1.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import chai, { expect } from 'chai';
import path from 'path';
import Helper from '../e2e-helper';
import { COMPONENT_DIST_PATH_TEMPLATE } from '../../src/constants';

const assertArrays = require('chai-arrays');
chai.use(require('chai-fs'));
Expand Down Expand Up @@ -214,17 +215,33 @@ describe('bit build', function () {
.that.equal('bar');
});
describe('importing the component to a new workspace', () => {
let packageJson;
before(() => {
helper.exportAllComponents();
helper.reInitLocalScope();
helper.addRemoteScope();
helper.importComponent('bar/foo');
packageJson = helper.readPackageJson(path.join(helper.localScopePath, 'components/bar/foo'));
});
it('should write the added props into the component package.json', () => {
const packageJson = helper.readPackageJson(path.join(helper.localScopePath, 'components/bar/foo'));
expect(packageJson).to.have.property('foo');
expect(packageJson.foo).equal('bar');
});
it(`should search for ${COMPONENT_DIST_PATH_TEMPLATE} template and replace with the path to the dist`, () => {
expect(packageJson).to.have.property('dynamicValue');
expect(packageJson.dynamicValue).equal('dist/bar/foo.js');
});
describe('importing when the dist is outside the components dir', () => {
before(() => {
helper.modifyFieldInBitJson('dist', { target: 'dist', entry: 'src' });
helper.importComponent('bar/foo -O');
packageJson = helper.readPackageJson(path.join(helper.localScopePath, 'components/bar/foo'));
});
it(`should search for ${COMPONENT_DIST_PATH_TEMPLATE} template and replace with the correct path of the dist`, () => {
expect(packageJson).to.have.property('dynamicValue');
expect(packageJson.dynamicValue).equal('../../../dist/components/bar/foo/bar/foo.js');
});
});
});
});
});
Expand Down
3 changes: 2 additions & 1 deletion e2e/fixtures/compilers/pkg-json/compiler.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ function compile(files, distPath) {
distFile.path = path.join(distPath, file.relative);
return distFile;
});
return { dists, packageJson: { foo: 'bar' } };
const filePath = files[0].relative.replace(/\\/g, '/'); // linux format
return { dists, packageJson: { foo: 'bar', dynamicValue: `{COMPONENT_DIST_PATH}/${filePath}` } };
}

module.exports = {
Expand Down
2 changes: 2 additions & 0 deletions src/constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -375,3 +375,5 @@ export const ACCEPTABLE_NPM_VERSIONS = '>=5.0.0';
export const ANGULAR_PACKAGE_IDENTIFIER = '@angular/core';

export const ANGULAR_BIT_ENTRY_POINT_FILE = 'public_api.ts';

export const COMPONENT_DIST_PATH_TEMPLATE = '{COMPONENT_DIST_PATH}';
46 changes: 43 additions & 3 deletions src/consumer/component-ops/component-writer.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
// @flow
import R from 'ramda';
import fs from 'fs-extra';
import semver from 'semver';
import * as RA from 'ramda-adjunct';
Expand All @@ -9,8 +10,14 @@ import type { ComponentOrigin } from '../bit-map/component-map';
import type Consumer from '../consumer';
import logger from '../../logger/logger';
import GeneralError from '../../error/general-error';
import { pathNormalizeToLinux } from '../../utils/path';
import { COMPONENT_ORIGINS, COMPILER_ENV_TYPE, TESTER_ENV_TYPE, DEFAULT_EJECTED_ENVS_DIR_PATH } from '../../constants';
import { pathNormalizeToLinux, getPathRelativeRegardlessCWD } from '../../utils/path';
import {
COMPONENT_ORIGINS,
COMPILER_ENV_TYPE,
TESTER_ENV_TYPE,
DEFAULT_EJECTED_ENVS_DIR_PATH,
COMPONENT_DIST_PATH_TEMPLATE
} from '../../constants';
import getNodeModulesPathOfComponent from '../../utils/bit/component-node-modules-path';
import type { PathOsBasedRelative } from '../../utils/path';
import { preparePackageJsonToWrite } from '../component/package-json-utils';
Expand All @@ -21,6 +28,7 @@ import ConfigDir from '../bit-map/config-dir';
import EnvExtension from '../../extensions/env-extension';
import ComponentConfig from '../config/component-config';
import { populateEnvFilesToWrite } from './eject-conf';
import PackageJsonFile from '../component/package-json-file';

export type ComponentWriterProps = {
component: Component,
Expand Down Expand Up @@ -170,7 +178,7 @@ export default class ComponentWriter {
componentConfig.compiler = this.component.compiler ? this.component.compiler.toBitJsonObject('.') : {};
componentConfig.tester = this.component.tester ? this.component.tester.toBitJsonObject('.') : {};
packageJson.addOrUpdateProperty('bit', componentConfig.toPlainObject());
packageJson.mergePackageJsonObject(this.component.packageJsonChangedProps);
this._mergeChangedPackageJsonProps(packageJson);
await this._populateEnvFilesIfNeeded();
this.component.dataToPersist.addFile(packageJson.toJSONFile());
if (distPackageJson) this.component.dataToPersist.addFile(distPackageJson.toJSONFile());
Expand Down Expand Up @@ -245,6 +253,38 @@ export default class ComponentWriter {
}
}

_mergeChangedPackageJsonProps(packageJson: PackageJsonFile) {
if (!this.component.packageJsonChangedProps) return;
const valuesToMerge = this._replaceDistPathTemplateWithCalculatedDistPath(packageJson);
packageJson.mergePackageJsonObject(valuesToMerge);
}

/**
* see https://github.com/teambit/bit/issues/1808 for more info why it's needed
*/
_replaceDistPathTemplateWithCalculatedDistPath(packageJson: PackageJsonFile): Object {
// $FlowFixMe
const packageJsonChangedProps: Object = this.component.packageJsonChangedProps;
const isReplaceNeeded = R.values(packageJsonChangedProps).some(val => val.includes(COMPONENT_DIST_PATH_TEMPLATE));
if (!isReplaceNeeded) {
return packageJsonChangedProps;
}
if (!this.component.dists || !this.component.dists.distsRootDir) {
throw new Error(
`package.json has a dynamic value ${COMPONENT_DIST_PATH_TEMPLATE}, however, the dist root is not set`
);
}
const distRelativeToPackageJson = getPathRelativeRegardlessCWD(
path.dirname(packageJson.filePath), // $FlowFixMe
this.component.dists.distsRootDir
);
return Object.keys(packageJsonChangedProps).reduce((acc, key) => {
const val = packageJsonChangedProps[key].replace(COMPONENT_DIST_PATH_TEMPLATE, distRelativeToPackageJson);
acc[key] = val;
return acc;
}, {});
}

_copyFilesIntoDistsWhenDistsOutsideComponentDir() {
if (!this.consumer) return; // not relevant when consumer is not available
if (!this.consumer.shouldDistsBeInsideTheComponent() && this.component.dists.isEmpty()) {
Expand Down
14 changes: 2 additions & 12 deletions src/links/node-modules-linker.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import LinkFile from './link-file';
import ComponentsList from '../consumer/component/components-list';
import { preparePackageJsonToWrite } from '../consumer/component/package-json-utils';
import PackageJsonFile from '../consumer/component/package-json-file';
import { getPathRelativeRegardlessCWD } from '../utils/path';

type LinkDetail = { from: string, to: string };
export type LinksResult = {
Expand Down Expand Up @@ -142,7 +143,7 @@ export default class NodeModuleLinker {
const isMain = file === component.componentMap.mainFile;
const possiblyDist = component.dists.calculateDistFileForAuthored(path.normalize(file), this.consumer, isMain);
const dest = path.join(getNodeModulesPathOfComponent(component.bindingPrefix, componentId), file);
const destRelative = this._getPathRelativeRegardlessCWD(path.dirname(dest), possiblyDist);
const destRelative = getPathRelativeRegardlessCWD(path.dirname(dest), possiblyDist);
const fileContent = getLinkToFileContent(destRelative);
if (fileContent) {
const linkFile = LinkFile.load({
Expand Down Expand Up @@ -289,17 +290,6 @@ export default class NodeModuleLinker {
return componentsDependenciesLinks;
}

/**
* path.resolve uses current working dir.
* for us, the cwd is not important. a user may running bit command from an inner dir.
*/
_getPathRelativeRegardlessCWD(from: PathOsBasedRelative, to: PathOsBasedRelative): PathLinuxRelative {
const fromLinux = pathNormalizeToLinux(from);
const toLinux = pathNormalizeToLinux(to);
// change them to absolute so path.relative won't consider the cwd
return pathRelativeLinux(`/${fromLinux}`, `/${toLinux}`);
}

/**
* create package.json on node_modules/@bit/component-name/package.json with a property 'main'
* pointing to the component's main file.
Expand Down
11 changes: 11 additions & 0 deletions src/utils/path.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,14 @@ export function pathRelativeLinux(from: PathOsBased, to: PathOsBased): PathLinux
export function pathResolveToLinux(arr: PathOsBased[]): PathLinux {
return normalize(path.resolve(arr.join(',')));
}

/**
* path.resolve uses current working dir.
* sometimes the cwd is not important. a user may running bit command from an inner dir.
*/
export function getPathRelativeRegardlessCWD(from: PathOsBasedRelative, to: PathOsBasedRelative): PathLinuxRelative {
const fromLinux = pathNormalizeToLinux(from);
const toLinux = pathNormalizeToLinux(to);
// change them to absolute so path.relative won't consider the cwd
return pathRelativeLinux(`/${fromLinux}`, `/${toLinux}`);
}

0 comments on commit b087476

Please sign in to comment.