config-impl.js 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. "use strict";
  2. /**
  3. * @license
  4. * Copyright Google Inc. All Rights Reserved.
  5. *
  6. * Use of this source code is governed by an MIT-style license that can be
  7. * found in the LICENSE file at https://angular.io/license
  8. */
  9. Object.defineProperty(exports, "__esModule", { value: true });
  10. const core_1 = require("@angular-devkit/core");
  11. const fs_1 = require("fs");
  12. const uuid_1 = require("uuid");
  13. const command_1 = require("../models/command");
  14. const interface_1 = require("../models/interface");
  15. const config_1 = require("../utilities/config");
  16. function _validateBoolean(value) {
  17. if (('' + value).trim() === 'true') {
  18. return true;
  19. }
  20. else if (('' + value).trim() === 'false') {
  21. return false;
  22. }
  23. else {
  24. throw new Error(`Invalid value type; expected Boolean, received ${JSON.stringify(value)}.`);
  25. }
  26. }
  27. function _validateNumber(value) {
  28. const numberValue = Number(value);
  29. if (!Number.isFinite(numberValue)) {
  30. return numberValue;
  31. }
  32. throw new Error(`Invalid value type; expected Number, received ${JSON.stringify(value)}.`);
  33. }
  34. function _validateString(value) {
  35. return value;
  36. }
  37. function _validateAnalytics(value) {
  38. if (value === '') {
  39. // Disable analytics.
  40. return null;
  41. }
  42. else {
  43. return value;
  44. }
  45. }
  46. function _validateAnalyticsSharingUuid(value) {
  47. if (value == '') {
  48. return uuid_1.v4();
  49. }
  50. else {
  51. return value;
  52. }
  53. }
  54. function _validateAnalyticsSharingTracking(value) {
  55. if (!value.match(/^GA-\d+-\d+$/)) {
  56. throw new Error(`Invalid GA property ID: ${JSON.stringify(value)}.`);
  57. }
  58. return value;
  59. }
  60. const validCliPaths = new Map([
  61. ['cli.warnings.versionMismatch', _validateBoolean],
  62. ['cli.defaultCollection', _validateString],
  63. ['cli.packageManager', _validateString],
  64. ['cli.analytics', _validateAnalytics],
  65. ['cli.analyticsSharing.tracking', _validateAnalyticsSharingTracking],
  66. ['cli.analyticsSharing.uuid', _validateAnalyticsSharingUuid],
  67. ]);
  68. /**
  69. * Splits a JSON path string into fragments. Fragments can be used to get the value referenced
  70. * by the path. For example, a path of "a[3].foo.bar[2]" would give you a fragment array of
  71. * ["a", 3, "foo", "bar", 2].
  72. * @param path The JSON string to parse.
  73. * @returns {(string|number)[]} The fragments for the string.
  74. * @private
  75. */
  76. function parseJsonPath(path) {
  77. const fragments = (path || '').split(/\./g);
  78. const result = [];
  79. while (fragments.length > 0) {
  80. const fragment = fragments.shift();
  81. if (fragment == undefined) {
  82. break;
  83. }
  84. const match = fragment.match(/([^\[]+)((\[.*\])*)/);
  85. if (!match) {
  86. throw new Error('Invalid JSON path.');
  87. }
  88. result.push(match[1]);
  89. if (match[2]) {
  90. const indices = match[2]
  91. .slice(1, -1)
  92. .split('][')
  93. .map(x => /^\d$/.test(x) ? +x : x.replace(/\"|\'/g, ''));
  94. result.push(...indices);
  95. }
  96. }
  97. return result.filter(fragment => fragment != null);
  98. }
  99. function getValueFromPath(root, path) {
  100. const fragments = parseJsonPath(path);
  101. try {
  102. return fragments.reduce((value, current) => {
  103. if (value == undefined || typeof value != 'object') {
  104. return undefined;
  105. }
  106. else if (typeof current == 'string' && !Array.isArray(value)) {
  107. return value[current];
  108. }
  109. else if (typeof current == 'number' && Array.isArray(value)) {
  110. return value[current];
  111. }
  112. else {
  113. return undefined;
  114. }
  115. }, root);
  116. }
  117. catch (_a) {
  118. return undefined;
  119. }
  120. }
  121. function setValueFromPath(root, path, newValue) {
  122. const fragments = parseJsonPath(path);
  123. try {
  124. return fragments.reduce((value, current, index) => {
  125. if (value == undefined || typeof value != 'object') {
  126. return undefined;
  127. }
  128. else if (typeof current == 'string' && !Array.isArray(value)) {
  129. if (index === fragments.length - 1) {
  130. value[current] = newValue;
  131. }
  132. else if (value[current] == undefined) {
  133. if (typeof fragments[index + 1] == 'number') {
  134. value[current] = [];
  135. }
  136. else if (typeof fragments[index + 1] == 'string') {
  137. value[current] = {};
  138. }
  139. }
  140. return value[current];
  141. }
  142. else if (typeof current == 'number' && Array.isArray(value)) {
  143. if (index === fragments.length - 1) {
  144. value[current] = newValue;
  145. }
  146. else if (value[current] == undefined) {
  147. if (typeof fragments[index + 1] == 'number') {
  148. value[current] = [];
  149. }
  150. else if (typeof fragments[index + 1] == 'string') {
  151. value[current] = {};
  152. }
  153. }
  154. return value[current];
  155. }
  156. else {
  157. return undefined;
  158. }
  159. }, root);
  160. }
  161. catch (_a) {
  162. return undefined;
  163. }
  164. }
  165. function normalizeValue(value, path) {
  166. const cliOptionType = validCliPaths.get(path);
  167. if (cliOptionType) {
  168. return cliOptionType('' + value);
  169. }
  170. if (typeof value === 'string') {
  171. try {
  172. return core_1.parseJson(value, core_1.JsonParseMode.Loose);
  173. }
  174. catch (e) {
  175. if (e instanceof core_1.InvalidJsonCharacterException && !value.startsWith('{')) {
  176. return value;
  177. }
  178. else {
  179. throw e;
  180. }
  181. }
  182. }
  183. return value;
  184. }
  185. class ConfigCommand extends command_1.Command {
  186. async run(options) {
  187. const level = options.global ? 'global' : 'local';
  188. if (!options.global) {
  189. await this.validateScope(interface_1.CommandScope.InProject);
  190. }
  191. let config = config_1.getWorkspace(level);
  192. if (options.global && !config) {
  193. try {
  194. if (config_1.migrateLegacyGlobalConfig()) {
  195. config =
  196. config_1.getWorkspace(level);
  197. this.logger.info(core_1.tags.oneLine `
  198. We found a global configuration that was used in Angular CLI 1.
  199. It has been automatically migrated.`);
  200. }
  201. }
  202. catch (_a) { }
  203. }
  204. if (options.value == undefined) {
  205. if (!config) {
  206. this.logger.error('No config found.');
  207. return 1;
  208. }
  209. return this.get(config._workspace, options);
  210. }
  211. else {
  212. return this.set(options);
  213. }
  214. }
  215. get(config, options) {
  216. let value;
  217. if (options.jsonPath) {
  218. if (options.jsonPath === 'cli.warnings.typescriptMismatch') {
  219. // NOTE: Remove this in 9.0.
  220. this.logger.warn('The "typescriptMismatch" warning has been removed in 8.0.');
  221. // Since there is no actual warning, this value is always false.
  222. this.logger.info('false');
  223. return 0;
  224. }
  225. value = getValueFromPath(config, options.jsonPath);
  226. }
  227. else {
  228. value = config;
  229. }
  230. if (value === undefined) {
  231. this.logger.error('Value cannot be found.');
  232. return 1;
  233. }
  234. else if (typeof value == 'object') {
  235. this.logger.info(JSON.stringify(value, null, 2));
  236. }
  237. else {
  238. this.logger.info(value.toString());
  239. }
  240. return 0;
  241. }
  242. set(options) {
  243. if (!options.jsonPath || !options.jsonPath.trim()) {
  244. throw new Error('Invalid Path.');
  245. }
  246. if (options.jsonPath === 'cli.warnings.typescriptMismatch') {
  247. // NOTE: Remove this in 9.0.
  248. this.logger.warn('The "typescriptMismatch" warning has been removed in 8.0.');
  249. return 0;
  250. }
  251. if (options.global
  252. && !options.jsonPath.startsWith('schematics.')
  253. && !validCliPaths.has(options.jsonPath)) {
  254. throw new Error('Invalid Path.');
  255. }
  256. const [config, configPath] = config_1.getWorkspaceRaw(options.global ? 'global' : 'local');
  257. if (!config || !configPath) {
  258. this.logger.error('Confguration file cannot be found.');
  259. return 1;
  260. }
  261. // TODO: Modify & save without destroying comments
  262. const configValue = config.value;
  263. const value = normalizeValue(options.value || '', options.jsonPath);
  264. const result = setValueFromPath(configValue, options.jsonPath, value);
  265. if (result === undefined) {
  266. this.logger.error('Value cannot be found.');
  267. return 1;
  268. }
  269. try {
  270. config_1.validateWorkspace(configValue);
  271. }
  272. catch (error) {
  273. this.logger.fatal(error.message);
  274. return 1;
  275. }
  276. const output = JSON.stringify(configValue, null, 2);
  277. fs_1.writeFileSync(configPath, output);
  278. return 0;
  279. }
  280. }
  281. exports.ConfigCommand = ConfigCommand;