create-file.ts 5.2 KB

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