@teambit/renaming
Version:
485 lines (481 loc) • 18.1 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = exports.RenamingMain = void 0;
function _fsExtra() {
const data = _interopRequireDefault(require("fs-extra"));
_fsExtra = function () {
return data;
};
return data;
}
function _path() {
const data = _interopRequireDefault(require("path"));
_path = function () {
return data;
};
return data;
}
function _config() {
const data = require("@teambit/config");
_config = function () {
return data;
};
return data;
}
function _logger() {
const data = require("@teambit/logger");
_logger = function () {
return data;
};
return data;
}
function _workspaceModules() {
const data = require("@teambit/workspace.modules.node-modules-linker");
_workspaceModules = function () {
return data;
};
return data;
}
function _cli() {
const data = require("@teambit/cli");
_cli = function () {
return data;
};
return data;
}
function _component() {
const data = require("@teambit/component");
_component = function () {
return data;
};
return data;
}
function _deprecation() {
const data = require("@teambit/deprecation");
_deprecation = function () {
return data;
};
return data;
}
function _graphql() {
const data = require("@teambit/graphql");
_graphql = function () {
return data;
};
return data;
}
function _lodash() {
const data = require("lodash");
_lodash = function () {
return data;
};
return data;
}
function _compiler() {
const data = require("@teambit/compiler");
_compiler = function () {
return data;
};
return data;
}
function _envs() {
const data = require("@teambit/envs");
_envs = function () {
return data;
};
return data;
}
function _newComponentHelper() {
const data = require("@teambit/new-component-helper");
_newComponentHelper = function () {
return data;
};
return data;
}
function _remove() {
const data = require("@teambit/remove");
_remove = function () {
return data;
};
return data;
}
function _refactoring() {
const data = require("@teambit/refactoring");
_refactoring = function () {
return data;
};
return data;
}
function _componentWriter() {
const data = require("@teambit/component-writer");
_componentWriter = function () {
return data;
};
return data;
}
function _workspace() {
const data = require("@teambit/workspace");
_workspace = function () {
return data;
};
return data;
}
function _pMapSeries() {
const data = _interopRequireDefault(require("p-map-series"));
_pMapSeries = function () {
return data;
};
return data;
}
function _install() {
const data = require("@teambit/install");
_install = function () {
return data;
};
return data;
}
function _legacyBitId() {
const data = require("@teambit/legacy-bit-id");
_legacyBitId = function () {
return data;
};
return data;
}
function _rename() {
const data = require("./rename.cmd");
_rename = function () {
return data;
};
return data;
}
function _renaming() {
const data = require("./renaming.aspect");
_renaming = function () {
return data;
};
return data;
}
function _renaming2() {
const data = require("./renaming.fragment");
_renaming2 = function () {
return data;
};
return data;
}
function _renaming3() {
const data = require("./renaming.graphql");
_renaming3 = function () {
return data;
};
return data;
}
function _scopeRename() {
const data = require("./scope-rename.cmd");
_scopeRename = function () {
return data;
};
return data;
}
function _oldScopeNotFound() {
const data = require("./exceptions/old-scope-not-found");
_oldScopeNotFound = function () {
return data;
};
return data;
}
function _scopeRenameOwner() {
const data = require("./scope-rename-owner.cmd");
_scopeRenameOwner = function () {
return data;
};
return data;
}
function _renamingTagged() {
const data = require("./exceptions/renaming-tagged");
_renamingTagged = function () {
return data;
};
return data;
}
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
class RenamingMain {
constructor(workspace, install, newComponentHelper, deprecation, refactoring, config, componentWriter, compiler, logger, envs, remove) {
this.workspace = workspace;
this.install = install;
this.newComponentHelper = newComponentHelper;
this.deprecation = deprecation;
this.refactoring = refactoring;
this.config = config;
this.componentWriter = componentWriter;
this.compiler = compiler;
this.logger = logger;
this.envs = envs;
this.remove = remove;
}
async rename(sourceIdStr, targetName, options = {}) {
if (!(0, _legacyBitId().isValidIdChunk)(targetName)) {
if (targetName.includes('.')) throw new Error(`error: new-name argument "${targetName}" includes a dot.
make sure this argument is the name only, without the scope-name. to change the scope-name, use --scope flag`);
throw new (_legacyBitId().InvalidName)(targetName);
}
const sourceId = await this.workspace.resolveComponentId(sourceIdStr);
const targetId = this.newComponentHelper.getNewComponentId(targetName, undefined, options?.scope || sourceId.scope);
await this.renameMultiple([{
sourceId,
targetId
}], options);
return {
sourceId,
targetId
};
}
async renameMultiple(multipleIds, options) {
const renameData = [];
const stagedComps = multipleIds.filter(({
sourceId
}) => sourceId.hasVersion() && !this.workspace.isExported(sourceId));
if (stagedComps.length) {
const idsStr = stagedComps.map(({
sourceId
}) => sourceId.toString());
throw new (_renamingTagged().RenamingTagged)(idsStr);
}
await (0, _pMapSeries().default)(multipleIds, async ({
sourceId,
targetId
}) => {
const isTagged = sourceId.hasVersion();
const sourceComp = await this.workspace.get(sourceId);
const isEnv = this.envs.isEnv(sourceComp);
const sourcePackageName = this.workspace.componentPackageName(sourceComp);
renameData.push({
sourceId,
targetId,
sourcePkg: sourcePackageName,
isTagged,
compIdsUsingItAsEnv: isEnv ? (await this.workspace.getComponentsUsingEnv(sourceId.toString(), true)).map(c => c.id) : undefined
});
});
await (0, _pMapSeries().default)(renameData, async ({
sourceId,
targetId,
isTagged,
sourcePkg
}) => {
const sourceComp = await this.workspace.get(sourceId);
if (!options.preserve) {
await this.refactoring.refactorVariableAndClasses(sourceComp, sourceId, targetId);
this.refactoring.refactorFilenames(sourceComp, sourceId, targetId);
}
if (isTagged) {
const config = await this.getConfig(sourceComp);
await this.newComponentHelper.writeAndAddNewComp(sourceComp, targetId, options, config);
options.deprecate ? await this.deprecation.deprecate(sourceId, targetId) : await this.remove.deleteComps(sourceId.toString(), {
updateMain: true
});
} else {
this.workspace.bitMap.renameNewComponent(sourceId, targetId);
await this.deleteLinkFromNodeModules(sourcePkg);
}
});
await this.workspace.bitMap.write(`rename`);
await this.renameAspectIdsInWorkspaceConfig(multipleIds);
await this.workspace._reloadConsumer(); // in order to reload .bitmap file and clear all caches.
await this.changeEnvsAccordingToNewIds(renameData);
await (0, _pMapSeries().default)(renameData, async itemData => {
itemData.targetComp = await this.workspace.get(itemData.targetId);
itemData.targetPkg = this.workspace.componentPackageName(itemData.targetComp);
});
const refactoredIds = [];
if (options.refactor) {
const allComponents = await this.workspace.list();
const packagesToReplace = renameData.map(({
sourcePkg,
targetPkg
}) => {
if (!targetPkg) throw new Error(`renameMultiple, targetPkg is missing`);
return {
// replace only packages ending with slash, quote or double-quote. otherwise, it could replace part of other packages.
oldStr: `${sourcePkg}(['"/])`,
newStr: `${targetPkg}$1`
};
});
const {
changedComponents
} = await this.refactoring.replaceMultipleStrings(allComponents, packagesToReplace);
await Promise.all(changedComponents.map(comp => this.workspace.write(comp)));
refactoredIds.push(...changedComponents.map(c => c.id));
}
if (!options.preserve) {
await (0, _pMapSeries().default)(renameData, async ({
sourceId,
targetId,
targetComp,
isTagged
}) => {
if (isTagged) {
// we have done this logic already for tagged components before. (search for refactorVariableAndClasses).
return;
}
if (!targetComp) throw new Error(`renameMultiple, targetComp is missing`);
await this.refactoring.refactorVariableAndClasses(targetComp, sourceId, targetId, options);
const compPath = this.newComponentHelper.getNewComponentPath(targetId);
this.refactoring.refactorFilenames(targetComp, sourceId, targetId);
await this.componentWriter.writeMany({
components: [targetComp.state._consumer],
skipDependencyInstallation: true,
writeToPath: _path().default.join(this.workspace.path, compPath),
reasonForBitmapChange: 'rename'
});
});
}
multipleIds.forEach(({
sourceId,
targetId
}) => {
this.workspace.bitMap.renameAspectInConfig(sourceId, targetId);
});
await this.workspace.bitMap.write(`rename`);
const targetComps = (0, _lodash().compact)(renameData.map(({
targetComp
}) => targetComp));
await (0, _workspaceModules().linkToNodeModulesByComponents)(targetComps, this.workspace); // link the new-name to node-modules
await this.compileGracefully(targetComps.map(c => c.id));
return {
refactoredIds,
renameData
};
}
getRenamingInfo(component) {
const renameConfig = component.state.aspects.get(_renaming().RenamingAspect.id)?.config;
if (!renameConfig) return null;
return {
renamedFrom: _component().ComponentID.fromObject(renameConfig.renamedFrom)
};
}
/**
* change the default-scope for new components.
* for tagged/exported components, delete (or deprecate - depends on the flag) the original ones and create new ones.
* optionally (if refactor is true), change the source code to match the new scope-name.
*/
async renameScope(oldScope, newScope, options = {}) {
if (!this.workspace) throw new (_workspace().OutsideWorkspaceError)();
const allComponentsIds = this.workspace.listIds();
const componentsUsingOldScope = allComponentsIds.filter(compId => compId.scope === oldScope);
if (!componentsUsingOldScope.length && this.workspace.defaultScope !== oldScope) {
throw new (_oldScopeNotFound().OldScopeNotFound)(oldScope);
}
if (this.workspace.defaultScope === oldScope) {
await this.workspace.setDefaultScope(newScope, false);
}
const multipleIds = componentsUsingOldScope.map(compId => {
const targetId = _component().ComponentID.fromObject({
name: compId.fullName
}, newScope);
return {
sourceId: compId,
targetId
};
});
return this.renameMultiple(multipleIds, options);
}
/**
* change the default-scope for new components. optionally (if refactor is true), change the source code to match the
* new scope-name.
* keep in mind that this is working for new components only, for tagged/exported it's impossible. See the errors
* thrown in such cases in this method.
*/
async renameOwner(oldOwner, newOwner, options) {
if (!this.workspace) throw new (_workspace().OutsideWorkspaceError)();
const isScopeUsesOldOwner = scope => scope.startsWith(`${oldOwner}.`);
const allComponentsIds = this.workspace.listIds();
const componentsUsingOldScope = allComponentsIds.filter(compId => isScopeUsesOldOwner(compId.scope));
if (!componentsUsingOldScope.length && !isScopeUsesOldOwner(this.workspace.defaultScope)) {
throw new (_oldScopeNotFound().OldScopeNotFound)(oldOwner);
}
const oldWorkspaceDefaultScope = this.workspace.defaultScope;
const newWorkspaceDefaultScope = isScopeUsesOldOwner(oldWorkspaceDefaultScope) ? this.renameOwnerInScopeName(oldWorkspaceDefaultScope, oldOwner, newOwner) : undefined;
if (newWorkspaceDefaultScope) {
await this.workspace.setDefaultScope(newWorkspaceDefaultScope, false);
}
const multipleIds = componentsUsingOldScope.map(compId => {
const newScope = this.renameOwnerInScopeName(compId.scope, oldOwner, newOwner);
const targetId = compId.hasScope() ? compId.changeScope(newScope) : compId.changeDefaultScope(newScope);
return {
sourceId: compId,
targetId
};
});
return this.renameMultiple(multipleIds, _objectSpread(_objectSpread({}, options), {}, {
preserve: true
}));
}
async renameAspectIdsInWorkspaceConfig(ids) {
const config = this.config.workspaceConfig;
if (!config) throw new Error('unable to get workspace config');
const wereChangesDone = ids.map(renameId => config.renameExtensionInRaw(renameId.sourceId.toStringWithoutVersion(), renameId.targetId.toStringWithoutVersion()));
const hasChanged = wereChangesDone.some(isChanged => isChanged);
if (hasChanged) await config.write({
reasonForChange: 'rename'
});
}
async changeEnvsAccordingToNewIds(renameData) {
await (0, _pMapSeries().default)(renameData, async renameItem => {
const componentIds = renameItem.compIdsUsingItAsEnv;
if (!componentIds?.length) return;
const newEnvId = renameItem.targetId;
const newComponentIds = componentIds.map(id => {
const found = renameData.find(r => r.sourceId.isEqualWithoutVersion(id));
return found ? found.targetId : id;
});
await this.workspace.setEnvToComponents(newEnvId, newComponentIds);
});
}
async deleteLinkFromNodeModules(packageName) {
await _fsExtra().default.remove(_path().default.join(this.workspace.path, 'node_modules', packageName));
}
async compileGracefully(ids) {
try {
await this.compiler.compileOnWorkspace(ids);
} catch (err) {
const idsStr = ids.map(id => id.toString()).join(', ');
this.logger.consoleFailure(`failed compiling the component(s) ${idsStr}. error: ${err.message}`);
}
}
renameOwnerInScopeName(scopeName, oldOwner, newOwner) {
return scopeName.replace(`${oldOwner}.`, `${newOwner}.`);
}
async getConfig(comp) {
const fromExisting = await this.newComponentHelper.getConfigFromExistingToNewComponent(comp);
return _objectSpread(_objectSpread({}, fromExisting), {}, {
[_renaming().RenamingAspect.id]: {
renamedFrom: comp.id.toObject()
}
});
}
static async provider([cli, workspace, deprecation, newComponentHelper, componentMain, graphql, refactoring, install, config, componentWriter, compiler, loggerMain, envs, remove]) {
const logger = loggerMain.createLogger(_renaming().RenamingAspect.id);
const renaming = new RenamingMain(workspace, install, newComponentHelper, deprecation, refactoring, config, componentWriter, compiler, logger, envs, remove);
cli.register(new (_rename().RenameCmd)(renaming));
const scopeCommand = cli.getCommand('scope');
scopeCommand?.commands?.push(new (_scopeRename().ScopeRenameCmd)(renaming));
scopeCommand?.commands?.push(new (_scopeRenameOwner().ScopeRenameOwnerCmd)(renaming));
graphql.register(() => (0, _renaming3().renamingSchema)(renaming));
componentMain.registerShowFragments([new (_renaming2().RenamingFragment)(renaming)]);
return renaming;
}
}
exports.RenamingMain = RenamingMain;
_defineProperty(RenamingMain, "slots", []);
_defineProperty(RenamingMain, "dependencies", [_cli().CLIAspect, _workspace().WorkspaceAspect, _deprecation().DeprecationAspect, _newComponentHelper().NewComponentHelperAspect, _component().ComponentAspect, _graphql().GraphqlAspect, _refactoring().RefactoringAspect, _install().InstallAspect, _config().ConfigAspect, _componentWriter().ComponentWriterAspect, _compiler().CompilerAspect, _logger().LoggerAspect, _envs().EnvsAspect, _remove().RemoveAspect]);
_defineProperty(RenamingMain, "runtime", _cli().MainRuntime);
_renaming().RenamingAspect.addRuntime(RenamingMain);
var _default = exports.default = RenamingMain;
//# sourceMappingURL=renaming.main.runtime.js.map