config.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // Copyright (c) Jupyter Development Team.
  2. // Distributed under the terms of the Modified BSD License.
  3. import { murmur2 } from './hash';
  4. import { IDebugger } from './tokens';
  5. /**
  6. * A class that holds debugger configuration for all kernels.
  7. */
  8. export class DebuggerConfig implements IDebugger.IConfig {
  9. /**
  10. * Returns an id based on the given code.
  11. *
  12. * @param code The source code.
  13. * @param kernel The kernel name from current session.
  14. */
  15. getCodeId(code: string, kernel: string): string {
  16. const fileParams = this._fileParams.get(kernel);
  17. if (!fileParams) {
  18. throw new Error(`Kernel (${kernel}) has no tmp file params.`);
  19. }
  20. const hash = this._hashMethods.get(kernel);
  21. if (!hash) {
  22. throw new Error(`Kernel (${kernel}) has no hashing params.`);
  23. }
  24. const { prefix, suffix } = fileParams;
  25. return `${prefix}${hash(code)}${suffix}`;
  26. }
  27. /**
  28. * Sets the hash parameters for a kernel.
  29. *
  30. * @param params - Hashing parameters for a kernel.
  31. */
  32. setHashParams(params: IDebugger.IConfig.HashParams): void {
  33. const { kernel, method, seed } = params;
  34. if (!kernel) {
  35. throw new TypeError(`Kernel name is not defined.`);
  36. }
  37. switch (method) {
  38. case 'Murmur2':
  39. this._hashMethods.set(kernel, code => murmur2(code, seed).toString());
  40. break;
  41. default:
  42. throw new Error(`Hash method (${method}) is not supported.`);
  43. }
  44. }
  45. /**
  46. * Sets the parameters used by the kernel to create temp files (e.g. cells).
  47. *
  48. * @param params - Temporary file prefix and suffix for a kernel.
  49. */
  50. setTmpFileParams(params: IDebugger.IConfig.FileParams): void {
  51. const { kernel, prefix, suffix } = params;
  52. if (!kernel) {
  53. throw new TypeError(`Kernel name is not defined.`);
  54. }
  55. this._fileParams.set(kernel, { kernel, prefix, suffix });
  56. }
  57. /**
  58. * Gets the parameters used for the temp files (e.e. cells) for a kernel.
  59. *
  60. * @param kernel - The kernel name from current session.
  61. */
  62. getTmpFileParams(kernel: string): IDebugger.IConfig.FileParams {
  63. return this._fileParams.get(kernel)!;
  64. }
  65. private _fileParams = new Map<string, IDebugger.IConfig.FileParams>();
  66. private _hashMethods = new Map<string, (code: string) => string>();
  67. }