create-file.ts 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. // @ts-check
  2. import { readFileByLine } from './fetch-text-by-line';
  3. import { surgeDomainsetToClashDomainset, surgeRulesetToClashClassicalTextRuleset } from './clash';
  4. import picocolors from 'picocolors';
  5. import type { Span } from '../trace';
  6. import path from 'path';
  7. import { sort } from './timsort';
  8. import { fastStringArrayJoin } from './misc';
  9. export async function compareAndWriteFile(span: Span, linesA: string[], filePath: string) {
  10. let isEqual = true;
  11. const file = Bun.file(filePath);
  12. const linesALen = linesA.length;
  13. if (!(await file.exists())) {
  14. console.log(`${filePath} does not exists, writing...`);
  15. isEqual = false;
  16. } else if (linesALen === 0) {
  17. console.log(`Nothing to write to ${filePath}...`);
  18. isEqual = false;
  19. } else {
  20. /* The `isEqual` variable is used to determine whether the content of a file is equal to the
  21. provided lines or not. It is initially set to `true`, and then it is updated based on different
  22. conditions: */
  23. isEqual = await span.traceChildAsync(`comparing ${filePath}`, async () => {
  24. let index = 0;
  25. for await (const lineB of readFileByLine(file)) {
  26. const lineA = linesA[index] as string | undefined;
  27. index++;
  28. if (lineA == null) {
  29. // The file becomes smaller
  30. return false;
  31. }
  32. if (lineA[0] === '#' && lineB[0] === '#') {
  33. continue;
  34. }
  35. if (
  36. lineA[0] === '/'
  37. && lineA[1] === '/'
  38. && lineB[0] === '/'
  39. && lineB[1] === '/'
  40. && lineA[3] === '#'
  41. && lineB[3] === '#'
  42. ) {
  43. continue;
  44. }
  45. if (lineA !== lineB) {
  46. return false;
  47. }
  48. }
  49. if (index !== linesALen) {
  50. // The file becomes larger
  51. return false;
  52. }
  53. return true;
  54. });
  55. }
  56. if (isEqual) {
  57. console.log(picocolors.dim(`same content, bail out writing: ${filePath}`));
  58. return;
  59. }
  60. await span.traceChildAsync(`writing ${filePath}`, async () => {
  61. // if (linesALen < 10000) {
  62. return Bun.write(file, fastStringArrayJoin(linesA, '\n') + '\n');
  63. // }
  64. // const writer = file.writer();
  65. // for (let i = 0; i < linesALen; i++) {
  66. // writer.write(linesA[i]);
  67. // writer.write('\n');
  68. // }
  69. // return writer.end();
  70. });
  71. }
  72. export const withBannerArray = (title: string, description: string[] | readonly string[], date: Date, content: string[]) => {
  73. return [
  74. '#########################################',
  75. `# ${title}`,
  76. `# Last Updated: ${date.toISOString()}`,
  77. `# Size: ${content.length}`,
  78. ...description.map(line => (line ? `# ${line}` : '#')),
  79. '#########################################',
  80. ...content,
  81. '################## EOF ##################'
  82. ];
  83. };
  84. const collectType = (rule: string) => {
  85. let buf = '';
  86. for (let i = 0, len = rule.length; i < len; i++) {
  87. if (rule[i] === ',') {
  88. return buf;
  89. }
  90. buf += rule[i];
  91. }
  92. return null;
  93. };
  94. const defaultSortTypeOrder = Symbol('defaultSortTypeOrder');
  95. const sortTypeOrder: Record<string | typeof defaultSortTypeOrder, number> = {
  96. DOMAIN: 1,
  97. 'DOMAIN-SUFFIX': 2,
  98. 'DOMAIN-KEYWORD': 10,
  99. // experimental domain wildcard support
  100. 'DOMAIN-WILDCARD': 20,
  101. 'USER-AGENT': 30,
  102. 'PROCESS-NAME': 40,
  103. [defaultSortTypeOrder]: 50, // default sort order for unknown type
  104. 'URL-REGEX': 100,
  105. AND: 300,
  106. OR: 300,
  107. 'IP-CIDR': 400,
  108. 'IP-CIDR6': 400
  109. };
  110. // sort DOMAIN-SUFFIX and DOMAIN first, then DOMAIN-KEYWORD, then IP-CIDR and IP-CIDR6 if any
  111. export const sortRuleSet = (ruleSet: string[]) => {
  112. return sort(
  113. ruleSet.map((rule) => {
  114. const type = collectType(rule);
  115. if (!type) {
  116. return [10, rule] as const;
  117. }
  118. if (!(type in sortTypeOrder)) {
  119. return [sortTypeOrder[defaultSortTypeOrder], rule] as const;
  120. }
  121. if (type === 'URL-REGEX') {
  122. let extraWeight = 0;
  123. if (rule.includes('.+') || rule.includes('.*')) {
  124. extraWeight += 10;
  125. }
  126. if (rule.includes('|')) {
  127. extraWeight += 1;
  128. }
  129. return [
  130. sortTypeOrder[type] + extraWeight,
  131. rule
  132. ] as const;
  133. }
  134. return [sortTypeOrder[type], rule] as const;
  135. }),
  136. (a, b) => a[0] - b[0]
  137. ).map(c => c[1]);
  138. };
  139. const MARK = 'this_ruleset_is_made_by_sukkaw.ruleset.skk.moe';
  140. export const createRuleset = (
  141. parentSpan: Span,
  142. title: string, description: string[] | readonly string[], date: Date, content: string[],
  143. type: 'ruleset' | 'domainset', surgePath: string, clashPath: string
  144. ) => parentSpan.traceChild(`create ruleset: ${path.basename(surgePath, path.extname(surgePath))}`).traceAsyncFn((childSpan) => {
  145. const surgeContent = withBannerArray(
  146. title, description, date,
  147. sortRuleSet(type === 'domainset'
  148. ? [MARK, ...content]
  149. : [`DOMAIN,${MARK}`, ...content])
  150. );
  151. const clashContent = childSpan.traceChildSync('convert incoming ruleset to clash', () => {
  152. let _clashContent;
  153. switch (type) {
  154. case 'domainset':
  155. _clashContent = [MARK, ...surgeDomainsetToClashDomainset(content)];
  156. break;
  157. case 'ruleset':
  158. _clashContent = [`DOMAIN,${MARK}`, ...surgeRulesetToClashClassicalTextRuleset(content)];
  159. break;
  160. default:
  161. throw new TypeError(`Unknown type: ${type as any}`);
  162. }
  163. return withBannerArray(title, description, date, _clashContent);
  164. });
  165. return Promise.all([
  166. compareAndWriteFile(childSpan, surgeContent, surgePath),
  167. compareAndWriteFile(childSpan, clashContent, clashPath)
  168. ]);
  169. });