create-file.ts 5.5 KB

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