@lbdudc/linea-core 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +358 -0
- package/dist/analysis/analyze.d.ts +105 -0
- package/dist/analysis/analyze.js +220 -0
- package/dist/analysis/analyze.js.map +1 -0
- package/dist/analysis/runtime.d.ts +97 -0
- package/dist/analysis/runtime.js +198 -0
- package/dist/analysis/runtime.js.map +1 -0
- package/dist/analysis/wheels/micropip-0.6.0-py3-none-any.whl +0 -0
- package/dist/analysis/wheels/packaging-23.2-py3-none-any.whl +0 -0
- package/dist/assets.d.ts +16 -0
- package/dist/assets.js +36 -0
- package/dist/assets.js.map +1 -0
- package/dist/constants.d.ts +77 -0
- package/dist/constants.js +76 -0
- package/dist/constants.js.map +1 -0
- package/dist/derivation/derive.d.ts +68 -0
- package/dist/derivation/derive.js +115 -0
- package/dist/derivation/derive.js.map +1 -0
- package/dist/derivation/engine.d.ts +48 -0
- package/dist/derivation/engine.js +98 -0
- package/dist/derivation/engine.js.map +1 -0
- package/dist/errors.d.ts +72 -0
- package/dist/errors.js +91 -0
- package/dist/errors.js.map +1 -0
- package/dist/feature-model/convert.d.ts +35 -0
- package/dist/feature-model/convert.js +47 -0
- package/dist/feature-model/convert.js.map +1 -0
- package/dist/feature-model/engine.d.ts +60 -0
- package/dist/feature-model/engine.js +139 -0
- package/dist/feature-model/engine.js.map +1 -0
- package/dist/feature-model/inspect.d.ts +67 -0
- package/dist/feature-model/inspect.js +113 -0
- package/dist/feature-model/inspect.js.map +1 -0
- package/dist/feature-model/io.d.ts +66 -0
- package/dist/feature-model/io.js +92 -0
- package/dist/feature-model/io.js.map +1 -0
- package/dist/feature-model/parse.d.ts +30 -0
- package/dist/feature-model/parse.js +36 -0
- package/dist/feature-model/parse.js.map +1 -0
- package/dist/feature-model/text.d.ts +54 -0
- package/dist/feature-model/text.js +126 -0
- package/dist/feature-model/text.js.map +1 -0
- package/dist/fs/archive.d.ts +23 -0
- package/dist/fs/archive.js +87 -0
- package/dist/fs/archive.js.map +1 -0
- package/dist/fs/diff.d.ts +40 -0
- package/dist/fs/diff.js +155 -0
- package/dist/fs/diff.js.map +1 -0
- package/dist/fs/format.d.ts +21 -0
- package/dist/fs/format.js +111 -0
- package/dist/fs/format.js.map +1 -0
- package/dist/fs/workspace.d.ts +77 -0
- package/dist/fs/workspace.js +103 -0
- package/dist/fs/workspace.js.map +1 -0
- package/dist/index.d.ts +50 -0
- package/dist/index.js +48 -0
- package/dist/index.js.map +1 -0
- package/dist/internal/guards.d.ts +15 -0
- package/dist/internal/guards.js +16 -0
- package/dist/internal/guards.js.map +1 -0
- package/dist/line/platform-files.d.ts +73 -0
- package/dist/line/platform-files.js +112 -0
- package/dist/line/platform-files.js.map +1 -0
- package/dist/line/scaffold.d.ts +88 -0
- package/dist/line/scaffold.js +145 -0
- package/dist/line/scaffold.js.map +1 -0
- package/dist/line/templates/core/extra.js +54 -0
- package/dist/line/templates/core/transformation.js +196 -0
- package/dist/line/templates/metamodels/dataModel/extra.js +328 -0
- package/dist/line/templates/metamodels/dataModel/transformation.js +211 -0
- package/dist/line/templates/metamodels/sensor/extra.js +36 -0
- package/dist/line/templates/metamodels/sensor/transformation.js +47 -0
- package/dist/line/templates/pipeline/.gitlab-ci.yml +51 -0
- package/dist/line/templates/pipeline/ci/test-client.sh +16 -0
- package/dist/line/templates/pipeline/ci/test-server.sh +16 -0
- package/dist/product/engine-spec.d.ts +25 -0
- package/dist/product/engine-spec.js +77 -0
- package/dist/product/engine-spec.js.map +1 -0
- package/dist/product/spec.d.ts +130 -0
- package/dist/product/spec.js +219 -0
- package/dist/product/spec.js.map +1 -0
- package/dist/product/version.d.ts +27 -0
- package/dist/product/version.js +49 -0
- package/dist/product/version.js.map +1 -0
- package/dist/products-index/products-index.d.ts +224 -0
- package/dist/products-index/products-index.js +395 -0
- package/dist/products-index/products-index.js.map +1 -0
- package/dist/selection/selection.d.ts +126 -0
- package/dist/selection/selection.js +152 -0
- package/dist/selection/selection.js.map +1 -0
- package/package.json +67 -0
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Feature model parsing.
|
|
3
|
+
*
|
|
4
|
+
* Migrated from `linea/server/src/agents/tools/splContext.js:buildFeatureModel`
|
|
5
|
+
* (~42-46), minus two things:
|
|
6
|
+
*
|
|
7
|
+
* - the base64 handling (`file.encoding === 'base64' ? atob(...) : ...`): in the
|
|
8
|
+
* monolith models arrive from the GitLab API, in linea-core everything is
|
|
9
|
+
* plain text on disk. Decoding is linea-server's problem (ADR-003).
|
|
10
|
+
* - the module-level `fmCache` (splContext.js ~30-40). ADR-014 forbids it:
|
|
11
|
+
* linea-core keeps no state between calls. Callers that want caching own it.
|
|
12
|
+
*/
|
|
13
|
+
import { isFeatureModelType } from '../constants.js';
|
|
14
|
+
import { InvalidArgumentError } from '../errors.js';
|
|
15
|
+
import { parseModel } from './engine.js';
|
|
16
|
+
/**
|
|
17
|
+
* Parses a feature model document.
|
|
18
|
+
*
|
|
19
|
+
* @param params.content Model document as plain text (UVL or XML).
|
|
20
|
+
* @param params.type Notation of `content`. Always explicit — linea-core never
|
|
21
|
+
* sniffs the notation from the content itself.
|
|
22
|
+
* @returns An opaque model value, to be handed back to other linea-core functions.
|
|
23
|
+
* @throws {InvalidArgumentError} if `content` is not a non-empty string, if
|
|
24
|
+
* `type` is not `'UVL'`/`'XML'`, or if an XML document cannot be parsed.
|
|
25
|
+
* @throws {UvlParseError} if a UVL document cannot be parsed.
|
|
26
|
+
*/
|
|
27
|
+
export const parseFeatureModel = ({ content, type }) => {
|
|
28
|
+
if (typeof content !== 'string' || content.trim() === '') {
|
|
29
|
+
throw new InvalidArgumentError('A feature model needs non-empty "content".');
|
|
30
|
+
}
|
|
31
|
+
if (!isFeatureModelType(type)) {
|
|
32
|
+
throw new InvalidArgumentError(`Unknown feature model type "${String(type)}". Use "UVL" or "XML".`);
|
|
33
|
+
}
|
|
34
|
+
return parseModel(content, type);
|
|
35
|
+
};
|
|
36
|
+
//# sourceMappingURL=parse.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"parse.js","sourceRoot":"","sources":["../../src/feature-model/parse.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,OAAO,EAAE,kBAAkB,EAAyB,MAAM,iBAAiB,CAAA;AAC3E,OAAO,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAA;AACnD,OAAO,EAAE,UAAU,EAA0B,MAAM,aAAa,CAAA;AAIhE;;;;;;;;;;GAUG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAAC,EAChC,OAAO,EACP,IAAI,EAIL,EAAqB,EAAE;IACtB,IAAI,OAAO,OAAO,KAAK,QAAQ,IAAI,OAAO,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC;QACzD,MAAM,IAAI,oBAAoB,CAAC,4CAA4C,CAAC,CAAA;IAC9E,CAAC;IACD,IAAI,CAAC,kBAAkB,CAAC,IAAI,CAAC,EAAE,CAAC;QAC9B,MAAM,IAAI,oBAAoB,CAAC,+BAA+B,MAAM,CAAC,IAAI,CAAC,wBAAwB,CAAC,CAAA;IACrG,CAAC;IACD,OAAO,UAAU,CAAC,OAAO,EAAE,IAAI,CAAC,CAAA;AAClC,CAAC,CAAA","sourcesContent":["/**\r\n * Feature model parsing.\r\n *\r\n * Migrated from `linea/server/src/agents/tools/splContext.js:buildFeatureModel`\r\n * (~42-46), minus two things:\r\n *\r\n * - the base64 handling (`file.encoding === 'base64' ? atob(...) : ...`): in the\r\n * monolith models arrive from the GitLab API, in linea-core everything is\r\n * plain text on disk. Decoding is linea-server's problem (ADR-003).\r\n * - the module-level `fmCache` (splContext.js ~30-40). ADR-014 forbids it:\r\n * linea-core keeps no state between calls. Callers that want caching own it.\r\n */\r\nimport { isFeatureModelType, type FeatureModelType } from '../constants.js'\r\nimport { InvalidArgumentError } from '../errors.js'\r\nimport { parseModel, type FeatureModelValue } from './engine.js'\r\n\r\nexport type { FeatureModelValue } from './engine.js'\r\n\r\n/**\r\n * Parses a feature model document.\r\n *\r\n * @param params.content Model document as plain text (UVL or XML).\r\n * @param params.type Notation of `content`. Always explicit — linea-core never\r\n * sniffs the notation from the content itself.\r\n * @returns An opaque model value, to be handed back to other linea-core functions.\r\n * @throws {InvalidArgumentError} if `content` is not a non-empty string, if\r\n * `type` is not `'UVL'`/`'XML'`, or if an XML document cannot be parsed.\r\n * @throws {UvlParseError} if a UVL document cannot be parsed.\r\n */\r\nexport const parseFeatureModel = ({\r\n content,\r\n type\r\n}: {\r\n content: string\r\n type: FeatureModelType\r\n}): FeatureModelValue => {\r\n if (typeof content !== 'string' || content.trim() === '') {\r\n throw new InvalidArgumentError('A feature model needs non-empty \"content\".')\r\n }\r\n if (!isFeatureModelType(type)) {\r\n throw new InvalidArgumentError(`Unknown feature model type \"${String(type)}\". Use \"UVL\" or \"XML\".`)\r\n }\r\n return parseModel(content, type)\r\n}\r\n"]}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Normalises line endings and expands tabs so the UVL parser always gets clean
|
|
3
|
+
* input.
|
|
4
|
+
*
|
|
5
|
+
* Migrated from `linea/flamapy-server/main.py:normalize_uvl` (~122-131). Its
|
|
6
|
+
* docstring explains why: Monaco on Windows emits CRLF, and Shift+Tab/Tab leave
|
|
7
|
+
* mixed tabs and spaces that the UVL language server tolerates but the parser
|
|
8
|
+
* does not.
|
|
9
|
+
*
|
|
10
|
+
* @param params.uvl Raw UVL document.
|
|
11
|
+
* @returns The normalised document (trimmed, LF endings, tabs expanded to 4).
|
|
12
|
+
* @throws {InvalidArgumentError} if `uvl` is not a string. Returning `''` for a
|
|
13
|
+
* non-string would let a caller bug flow into `estimateFeatureCount` and
|
|
14
|
+
* silently flip an `ANALYSIS_THRESHOLDS` decision.
|
|
15
|
+
*/
|
|
16
|
+
export declare const normalizeUvl: ({ uvl }: {
|
|
17
|
+
uvl: string;
|
|
18
|
+
}) => string;
|
|
19
|
+
/**
|
|
20
|
+
* Counts features in a UVL document without parsing it.
|
|
21
|
+
*
|
|
22
|
+
* Migrated from `linea/server/src/utils/flamapyUtils.mjs:estimateFeatureCount`
|
|
23
|
+
* (~11-28), which is itself the twin of
|
|
24
|
+
* `linea/flamapy-server/main.py:estimate_feature_count` (~59-78). The counting
|
|
25
|
+
* loop is byte-compatible with both: everything after the `constraints` keyword
|
|
26
|
+
* is ignored, and a line counts as a feature when it is indented at least 2
|
|
27
|
+
* columns and its first token is not a group keyword.
|
|
28
|
+
*
|
|
29
|
+
* Normalise first: with tab indentation the root feature sits at indent 1 and is
|
|
30
|
+
* not counted, which is why `/analyze` in `main.py` calls `normalize_uvl` before
|
|
31
|
+
* counting.
|
|
32
|
+
*
|
|
33
|
+
* @param params.uvl Raw UVL document.
|
|
34
|
+
* @returns Estimated number of features.
|
|
35
|
+
* @throws {InvalidArgumentError} if `uvl` is not a string.
|
|
36
|
+
*/
|
|
37
|
+
export declare const estimateFeatureCount: ({ uvl }: {
|
|
38
|
+
uvl: string;
|
|
39
|
+
}) => number;
|
|
40
|
+
/**
|
|
41
|
+
* Builds the seed UVL model of a brand new line.
|
|
42
|
+
*
|
|
43
|
+
* Migrated byte for byte from `linea/server/src/model/services/LineService.js:43`:
|
|
44
|
+
* `` `features\n\t${line.name}\n\t\tmandatory\n\t\t\tvoid` ``.
|
|
45
|
+
* Tabs and the absence of a trailing newline are part of the contract — a test
|
|
46
|
+
* asserts the exact string.
|
|
47
|
+
*
|
|
48
|
+
* @param params.name Line name; used as the root feature.
|
|
49
|
+
* @returns The seed UVL document.
|
|
50
|
+
* @throws {InvalidArgumentError} if `name` is not a non-empty string.
|
|
51
|
+
*/
|
|
52
|
+
export declare const emptyFeatureModelUvl: ({ name }: {
|
|
53
|
+
name: string;
|
|
54
|
+
}) => string;
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure text helpers over UVL documents. No parsing, no I/O.
|
|
3
|
+
*/
|
|
4
|
+
import { InvalidArgumentError } from '../errors.js';
|
|
5
|
+
/** UVL keywords that introduce a group instead of naming a feature. */
|
|
6
|
+
const UVL_GROUP_KEYWORDS = new Set([
|
|
7
|
+
'mandatory',
|
|
8
|
+
'optional',
|
|
9
|
+
'alternative',
|
|
10
|
+
'or',
|
|
11
|
+
'features',
|
|
12
|
+
'constraints'
|
|
13
|
+
]);
|
|
14
|
+
const assertUvlString = (uvl, parameter) => {
|
|
15
|
+
if (typeof uvl !== 'string') {
|
|
16
|
+
throw new InvalidArgumentError(`"${parameter}" must be a string.`);
|
|
17
|
+
}
|
|
18
|
+
return uvl;
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* Faithful port of Python's `str.expandtabs(tabsize)`.
|
|
22
|
+
*
|
|
23
|
+
* NOT the same as replacing each tab with N spaces: a tab advances to the next
|
|
24
|
+
* multiple of `tabSize`. Getting this wrong would silently change the indentation
|
|
25
|
+
* of every UVL model, which is significant in UVL.
|
|
26
|
+
*/
|
|
27
|
+
const expandTabs = (line, tabSize = 4) => {
|
|
28
|
+
let out = '';
|
|
29
|
+
let column = 0;
|
|
30
|
+
for (const char of line) {
|
|
31
|
+
if (char === '\t') {
|
|
32
|
+
const width = tabSize - (column % tabSize);
|
|
33
|
+
out += ' '.repeat(width);
|
|
34
|
+
column += width;
|
|
35
|
+
}
|
|
36
|
+
else {
|
|
37
|
+
out += char;
|
|
38
|
+
column += 1;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
return out;
|
|
42
|
+
};
|
|
43
|
+
/**
|
|
44
|
+
* Normalises line endings and expands tabs so the UVL parser always gets clean
|
|
45
|
+
* input.
|
|
46
|
+
*
|
|
47
|
+
* Migrated from `linea/flamapy-server/main.py:normalize_uvl` (~122-131). Its
|
|
48
|
+
* docstring explains why: Monaco on Windows emits CRLF, and Shift+Tab/Tab leave
|
|
49
|
+
* mixed tabs and spaces that the UVL language server tolerates but the parser
|
|
50
|
+
* does not.
|
|
51
|
+
*
|
|
52
|
+
* @param params.uvl Raw UVL document.
|
|
53
|
+
* @returns The normalised document (trimmed, LF endings, tabs expanded to 4).
|
|
54
|
+
* @throws {InvalidArgumentError} if `uvl` is not a string. Returning `''` for a
|
|
55
|
+
* non-string would let a caller bug flow into `estimateFeatureCount` and
|
|
56
|
+
* silently flip an `ANALYSIS_THRESHOLDS` decision.
|
|
57
|
+
*/
|
|
58
|
+
export const normalizeUvl = ({ uvl }) => {
|
|
59
|
+
const unified = assertUvlString(uvl, 'uvl').trim().replace(/\r\n/g, '\n').replace(/\r/g, '\n');
|
|
60
|
+
return unified
|
|
61
|
+
.split('\n')
|
|
62
|
+
.map((line) => expandTabs(line, 4))
|
|
63
|
+
.join('\n');
|
|
64
|
+
};
|
|
65
|
+
/**
|
|
66
|
+
* Counts features in a UVL document without parsing it.
|
|
67
|
+
*
|
|
68
|
+
* Migrated from `linea/server/src/utils/flamapyUtils.mjs:estimateFeatureCount`
|
|
69
|
+
* (~11-28), which is itself the twin of
|
|
70
|
+
* `linea/flamapy-server/main.py:estimate_feature_count` (~59-78). The counting
|
|
71
|
+
* loop is byte-compatible with both: everything after the `constraints` keyword
|
|
72
|
+
* is ignored, and a line counts as a feature when it is indented at least 2
|
|
73
|
+
* columns and its first token is not a group keyword.
|
|
74
|
+
*
|
|
75
|
+
* Normalise first: with tab indentation the root feature sits at indent 1 and is
|
|
76
|
+
* not counted, which is why `/analyze` in `main.py` calls `normalize_uvl` before
|
|
77
|
+
* counting.
|
|
78
|
+
*
|
|
79
|
+
* @param params.uvl Raw UVL document.
|
|
80
|
+
* @returns Estimated number of features.
|
|
81
|
+
* @throws {InvalidArgumentError} if `uvl` is not a string.
|
|
82
|
+
*/
|
|
83
|
+
export const estimateFeatureCount = ({ uvl }) => {
|
|
84
|
+
const document = assertUvlString(uvl, 'uvl');
|
|
85
|
+
let inConstraints = false;
|
|
86
|
+
let count = 0;
|
|
87
|
+
for (const line of document.split('\n')) {
|
|
88
|
+
const trimmed = line.trim();
|
|
89
|
+
if (!trimmed || trimmed.startsWith('//') || trimmed.startsWith('#'))
|
|
90
|
+
continue;
|
|
91
|
+
if (trimmed === 'constraints') {
|
|
92
|
+
inConstraints = true;
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
if (inConstraints)
|
|
96
|
+
continue;
|
|
97
|
+
if (trimmed === 'features')
|
|
98
|
+
continue;
|
|
99
|
+
const indent = line.length - line.trimStart().length;
|
|
100
|
+
if (indent >= 2) {
|
|
101
|
+
const name = trimmed.split(/[\s{[]/)[0];
|
|
102
|
+
if (name && !UVL_GROUP_KEYWORDS.has(name))
|
|
103
|
+
count += 1;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
return count;
|
|
107
|
+
};
|
|
108
|
+
/**
|
|
109
|
+
* Builds the seed UVL model of a brand new line.
|
|
110
|
+
*
|
|
111
|
+
* Migrated byte for byte from `linea/server/src/model/services/LineService.js:43`:
|
|
112
|
+
* `` `features\n\t${line.name}\n\t\tmandatory\n\t\t\tvoid` ``.
|
|
113
|
+
* Tabs and the absence of a trailing newline are part of the contract — a test
|
|
114
|
+
* asserts the exact string.
|
|
115
|
+
*
|
|
116
|
+
* @param params.name Line name; used as the root feature.
|
|
117
|
+
* @returns The seed UVL document.
|
|
118
|
+
* @throws {InvalidArgumentError} if `name` is not a non-empty string.
|
|
119
|
+
*/
|
|
120
|
+
export const emptyFeatureModelUvl = ({ name }) => {
|
|
121
|
+
if (typeof name !== 'string' || name.trim() === '') {
|
|
122
|
+
throw new InvalidArgumentError('"name" must be a non-empty string.');
|
|
123
|
+
}
|
|
124
|
+
return `features\n\t${name}\n\t\tmandatory\n\t\t\tvoid`;
|
|
125
|
+
};
|
|
126
|
+
//# sourceMappingURL=text.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"text.js","sourceRoot":"","sources":["../../src/feature-model/text.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,OAAO,EAAE,oB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CAAC,CAAA;AAED;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAG,CAAC,EAAE,IAAI,EAAoB,EAAU,EAAE;IACzE,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,IAAI,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC;QACnD,MAAM,IAAI,oBAAoB,CAAC,oCAAoC,CAAC,CAAA;IACtE,CAAC;IACD,OAAO,eAAe,IAAI,6BAA6B,CAAA;AACzD,CAAC,CAAA","sourcesContent":["/**\r\n * Pure text helpers over UVL documents. No parsing, no I/O.\r\n */\r\nimport { InvalidArgumentError } from '../errors.js'\r\n\r\n/** UVL keywords that introduce a group instead of naming a feature. */\r\nconst UVL_GROUP_KEYWORDS: ReadonlySet<string> = new Set([\r\n 'mandatory',\r\n 'optional',\r\n 'alternative',\r\n 'or',\r\n 'features',\r\n 'constraints'\r\n])\r\n\r\nconst assertUvlString = (uvl: unknown, parameter: string): string => {\r\n if (typeof uvl !== 'string') {\r\n throw new InvalidArgumentError(`\"${parameter}\" must be a string.`)\r\n }\r\n return uvl\r\n}\r\n\r\n/**\r\n * Faithful port of Python's `str.expandtabs(tabsize)`.\r\n *\r\n * NOT the same as replacing each tab with N spaces: a tab advances to the next\r\n * multiple of `tabSize`. Getting this wrong would silently change the indentation\r\n * of every UVL model, which is significant in UVL.\r\n */\r\nconst expandTabs = (line: string, tabSize = 4): string => {\r\n let out = ''\r\n let column = 0\r\n for (const char of line) {\r\n if (char === '\\t') {\r\n const width = tabSize - (column % tabSize)\r\n out += ' '.repeat(width)\r\n column += width\r\n } else {\r\n out += char\r\n column += 1\r\n }\r\n }\r\n return out\r\n}\r\n\r\n/**\r\n * Normalises line endings and expands tabs so the UVL parser always gets clean\r\n * input.\r\n *\r\n * Migrated from `linea/flamapy-server/main.py:normalize_uvl` (~122-131). Its\r\n * docstring explains why: Monaco on Windows emits CRLF, and Shift+Tab/Tab leave\r\n * mixed tabs and spaces that the UVL language server tolerates but the parser\r\n * does not.\r\n *\r\n * @param params.uvl Raw UVL document.\r\n * @returns The normalised document (trimmed, LF endings, tabs expanded to 4).\r\n * @throws {InvalidArgumentError} if `uvl` is not a string. Returning `''` for a\r\n * non-string would let a caller bug flow into `estimateFeatureCount` and\r\n * silently flip an `ANALYSIS_THRESHOLDS` decision.\r\n */\r\nexport const normalizeUvl = ({ uvl }: { uvl: string }): string => {\r\n const unified = assertUvlString(uvl, 'uvl').trim().replace(/\\r\\n/g, '\\n').replace(/\\r/g, '\\n')\r\n return unified\r\n .split('\\n')\r\n .map((line) => expandTabs(line, 4))\r\n .join('\\n')\r\n}\r\n\r\n/**\r\n * Counts features in a UVL document without parsing it.\r\n *\r\n * Migrated from `linea/server/src/utils/flamapyUtils.mjs:estimateFeatureCount`\r\n * (~11-28), which is itself the twin of\r\n * `linea/flamapy-server/main.py:estimate_feature_count` (~59-78). The counting\r\n * loop is byte-compatible with both: everything after the `constraints` keyword\r\n * is ignored, and a line counts as a feature when it is indented at least 2\r\n * columns and its first token is not a group keyword.\r\n *\r\n * Normalise first: with tab indentation the root feature sits at indent 1 and is\r\n * not counted, which is why `/analyze` in `main.py` calls `normalize_uvl` before\r\n * counting.\r\n *\r\n * @param params.uvl Raw UVL document.\r\n * @returns Estimated number of features.\r\n * @throws {InvalidArgumentError} if `uvl` is not a string.\r\n */\r\nexport const estimateFeatureCount = ({ uvl }: { uvl: string }): number => {\r\n const document = assertUvlString(uvl, 'uvl')\r\n let inConstraints = false\r\n let count = 0\r\n for (const line of document.split('\\n')) {\r\n const trimmed = line.trim()\r\n if (!trimmed || trimmed.startsWith('//') || trimmed.startsWith('#')) continue\r\n if (trimmed === 'constraints') {\r\n inConstraints = true\r\n continue\r\n }\r\n if (inConstraints) continue\r\n if (trimmed === 'features') continue\r\n const indent = line.length - line.trimStart().length\r\n if (indent >= 2) {\r\n const name = trimmed.split(/[\\s{[]/)[0]\r\n if (name && !UVL_GROUP_KEYWORDS.has(name)) count += 1\r\n }\r\n }\r\n return count\r\n}\r\n\r\n/**\r\n * Builds the seed UVL model of a brand new line.\r\n *\r\n * Migrated byte for byte from `linea/server/src/model/services/LineService.js:43`:\r\n * `` `features\\n\\t${line.name}\\n\\t\\tmandatory\\n\\t\\t\\tvoid` ``.\r\n * Tabs and the absence of a trailing newline are part of the contract — a test\r\n * asserts the exact string.\r\n *\r\n * @param params.name Line name; used as the root feature.\r\n * @returns The seed UVL document.\r\n * @throws {InvalidArgumentError} if `name` is not a non-empty string.\r\n */\r\nexport const emptyFeatureModelUvl = ({ name }: { name: string }): string => {\r\n if (typeof name !== 'string' || name.trim() === '') {\r\n throw new InvalidArgumentError('\"name\" must be a non-empty string.')\r\n }\r\n return `features\\n\\t${name}\\n\\t\\tmandatory\\n\\t\\t\\tvoid`\r\n}\r\n"]}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Extracts a zip archive.
|
|
3
|
+
*
|
|
4
|
+
* GitLab archives wrap everything in a single top-level directory named after
|
|
5
|
+
* the project and commit, so the interesting content is one level down. `prefix`
|
|
6
|
+
* selects it, reproducing the `srcPath` argument of `unZip`: the first top-level
|
|
7
|
+
* directory whose name starts with `prefix`, falling back to the first one.
|
|
8
|
+
*
|
|
9
|
+
* @param params.source Path to a `.zip` file, or its bytes.
|
|
10
|
+
* @param params.destDir Directory to extract into. Created if missing.
|
|
11
|
+
* @param params.prefix Optional: pick the top-level directory starting with it
|
|
12
|
+
* and return that instead of `destDir`.
|
|
13
|
+
* @returns The directory holding the extracted content.
|
|
14
|
+
* @throws {InvalidArgumentError} when the arguments are malformed or `source`
|
|
15
|
+
* does not exist.
|
|
16
|
+
*/
|
|
17
|
+
export declare const extractArchive: ({ source, destDir, prefix }: {
|
|
18
|
+
source: string | Uint8Array;
|
|
19
|
+
destDir: string;
|
|
20
|
+
prefix?: string;
|
|
21
|
+
}) => Promise<{
|
|
22
|
+
dir: string;
|
|
23
|
+
}>;
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Archive extraction.
|
|
3
|
+
*
|
|
4
|
+
* Migrated from `linea/server/src/model/services/utils.js:unZip` (~46-80), which
|
|
5
|
+
* downloads a repository archive from GitLab and unpacks it.
|
|
6
|
+
*
|
|
7
|
+
* HARDENED PORT on two counts (ADR-014):
|
|
8
|
+
* - `unZip` created its scratch space itself under the GLOBAL
|
|
9
|
+
* `properties.paths.output`, so where the files landed depended on
|
|
10
|
+
* configuration the caller could not see. Here `destDir` is a required
|
|
11
|
+
* parameter and nothing else is ever touched.
|
|
12
|
+
* - It also took the archive as a readable STREAM and wrote it to
|
|
13
|
+
* `archive.zip` inside the target directory, leaving that file behind for the
|
|
14
|
+
* caller to delete (`PlaygroundService.js:164` does exactly that). Here the
|
|
15
|
+
* source is a path or a buffer, and any temporary copy is cleaned up.
|
|
16
|
+
*/
|
|
17
|
+
import fs from 'node:fs';
|
|
18
|
+
import os from 'node:os';
|
|
19
|
+
import path from 'node:path';
|
|
20
|
+
import extract from 'extract-zip';
|
|
21
|
+
import { InvalidArgumentError } from '../errors.js';
|
|
22
|
+
/**
|
|
23
|
+
* Extracts a zip archive.
|
|
24
|
+
*
|
|
25
|
+
* GitLab archives wrap everything in a single top-level directory named after
|
|
26
|
+
* the project and commit, so the interesting content is one level down. `prefix`
|
|
27
|
+
* selects it, reproducing the `srcPath` argument of `unZip`: the first top-level
|
|
28
|
+
* directory whose name starts with `prefix`, falling back to the first one.
|
|
29
|
+
*
|
|
30
|
+
* @param params.source Path to a `.zip` file, or its bytes.
|
|
31
|
+
* @param params.destDir Directory to extract into. Created if missing.
|
|
32
|
+
* @param params.prefix Optional: pick the top-level directory starting with it
|
|
33
|
+
* and return that instead of `destDir`.
|
|
34
|
+
* @returns The directory holding the extracted content.
|
|
35
|
+
* @throws {InvalidArgumentError} when the arguments are malformed or `source`
|
|
36
|
+
* does not exist.
|
|
37
|
+
*/
|
|
38
|
+
export const extractArchive = async ({ source, destDir, prefix }) => {
|
|
39
|
+
if (typeof destDir !== 'string' || destDir.trim() === '') {
|
|
40
|
+
throw new InvalidArgumentError('"destDir" must be a non-empty path.');
|
|
41
|
+
}
|
|
42
|
+
if (prefix !== undefined && typeof prefix !== 'string') {
|
|
43
|
+
throw new InvalidArgumentError('"prefix" must be a string when provided.');
|
|
44
|
+
}
|
|
45
|
+
const target = path.resolve(destDir);
|
|
46
|
+
fs.mkdirSync(target, { recursive: true });
|
|
47
|
+
// A buffer has to reach the disk for yauzl to read it; that copy is ours to
|
|
48
|
+
// clean up, and it goes to the OS temp dir so it never pollutes `destDir`.
|
|
49
|
+
let archivePath;
|
|
50
|
+
let scratchDir = null;
|
|
51
|
+
if (typeof source === 'string') {
|
|
52
|
+
if (source.trim() === '') {
|
|
53
|
+
throw new InvalidArgumentError('"source" must be a non-empty path.');
|
|
54
|
+
}
|
|
55
|
+
archivePath = path.resolve(source);
|
|
56
|
+
if (!fs.existsSync(archivePath)) {
|
|
57
|
+
throw new InvalidArgumentError(`Archive not found: ${archivePath}`);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
else if (source instanceof Uint8Array) {
|
|
61
|
+
scratchDir = fs.mkdtempSync(path.join(os.tmpdir(), 'linea-core-archive-'));
|
|
62
|
+
archivePath = path.join(scratchDir, 'archive.zip');
|
|
63
|
+
fs.writeFileSync(archivePath, source);
|
|
64
|
+
}
|
|
65
|
+
else {
|
|
66
|
+
throw new InvalidArgumentError('"source" must be a path or a Uint8Array.');
|
|
67
|
+
}
|
|
68
|
+
try {
|
|
69
|
+
await extract(archivePath, { dir: target });
|
|
70
|
+
}
|
|
71
|
+
finally {
|
|
72
|
+
if (scratchDir !== null)
|
|
73
|
+
fs.rmSync(scratchDir, { recursive: true, force: true });
|
|
74
|
+
}
|
|
75
|
+
if (prefix === undefined)
|
|
76
|
+
return { dir: target };
|
|
77
|
+
const directories = fs
|
|
78
|
+
.readdirSync(target, { withFileTypes: true })
|
|
79
|
+
.filter((entry) => entry.isDirectory())
|
|
80
|
+
.map((entry) => entry.name)
|
|
81
|
+
.sort();
|
|
82
|
+
// Same resolution as unZip: first match on the prefix, else the first
|
|
83
|
+
// directory, else the extraction root itself.
|
|
84
|
+
const chosen = directories.find((name) => name.startsWith(prefix)) ?? directories[0];
|
|
85
|
+
return { dir: chosen === undefined ? target : path.join(target, chosen) };
|
|
86
|
+
};
|
|
87
|
+
//# sourceMappingURL=archive.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"archive.js","sourceRoot":"","sources":["../../src/fs/archive.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AACH,OAAO,EAAE,MAAM,SAAS,CAAA;AACxB,OAAO,EAAE,MAAM,SAAS,CAAA;AACxB,OAAO,IAAI,MAAM,WAAW,CAAA;AAC5B,OAAO,OAAO,MAAM,aAAa,CAAA;AACjC,OAAO,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAA;AAEnD;;;;;;;;;;;;;;;GAeG;AACH,MAAM,CAAC,MAAM,cAAc,GAAG,KAAK,EAAE,EACnC,MAAM,EACN,OAAO,EACP,MAAM,EAKP,EAA4B,EAAE;IAC7B,IAAI,OAAO,OAAO,KAAK,QAAQ,IAAI,OAAO,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC;QACzD,MAAM,IAAI,oBAAoB,CAAC,qCAAqC,CAAC,CAAA;IACvE,CAAC;IACD,IAAI,MAAM,KAAK,SAAS,IAAI,OAAO,MAAM,KAAK,QAAQ,EAAE,CAAC;QACvD,MAAM,IAAI,oBAAoB,CAAC,0CAA0C,CAAC,CAAA;IAC5E,CAAC;IAED,MAAM,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,CAAA;IACpC,EAAE,CAAC,SAAS,CAAC,MAAM,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAA;IAEzC,4EAA4E;IAC5E,2EAA2E;IAC3E,IAAI,WAAmB,CAAA;IACvB,IAAI,UAAU,GAAkB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SAC5C,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,WAAW,EAAE,CAAC;SACtC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC;SAC1B,IAAI,EAAE,CAAA;IAET,sEAAsE;IACtE,8CAA8C;IAC9C,MAAM,MAAM,GAAG,WAAW,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,IAAI,WAAW,CAAC,CAAC,CAAC,CAAA;IACpF,OAAO,EAAE,GAAG,EAAE,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,MAAM,CAAC,EAAE,CAAA;AAC3E,CAAC,CAAA","sourcesContent":["/**\r\n * Archive extraction.\r\n *\r\n * Migrated from `linea/server/src/model/services/utils.js:unZip` (~46-80), which\r\n * downloads a repository archive from GitLab and unpacks it.\r\n *\r\n * HARDENED PORT on two counts (ADR-014):\r\n * - `unZip` created its scratch space itself under the GLOBAL\r\n * `properties.paths.output`, so where the files landed depended on\r\n * configuration the caller could not see. Here `destDir` is a required\r\n * parameter and nothing else is ever touched.\r\n * - It also took the archive as a readable STREAM and wrote it to\r\n * `archive.zip` inside the target directory, leaving that file behind for the\r\n * caller to delete (`PlaygroundService.js:164` does exactly that). Here the\r\n * source is a path or a buffer, and any temporary copy is cleaned up.\r\n */\r\nimport fs from 'node:fs'\r\nimport os from 'node:os'\r\nimport path from 'node:path'\r\nimport extract from 'extract-zip'\r\nimport { InvalidArgumentError } from '../errors.js'\r\n\r\n/**\r\n * Extracts a zip archive.\r\n *\r\n * GitLab archives wrap everything in a single top-level directory named after\r\n * the project and commit, so the interesting content is one level down. `prefix`\r\n * selects it, reproducing the `srcPath` argument of `unZip`: the first top-level\r\n * directory whose name starts with `prefix`, falling back to the first one.\r\n *\r\n * @param params.source Path to a `.zip` file, or its bytes.\r\n * @param params.destDir Directory to extract into. Created if missing.\r\n * @param params.prefix Optional: pick the top-level directory starting with it\r\n * and return that instead of `destDir`.\r\n * @returns The directory holding the extracted content.\r\n * @throws {InvalidArgumentError} when the arguments are malformed or `source`\r\n * does not exist.\r\n */\r\nexport const extractArchive = async ({\r\n source,\r\n destDir,\r\n prefix\r\n}: {\r\n source: string | Uint8Array\r\n destDir: string\r\n prefix?: string\r\n}): Promise<{ dir: string }> => {\r\n if (typeof destDir !== 'string' || destDir.trim() === '') {\r\n throw new InvalidArgumentError('\"destDir\" must be a non-empty path.')\r\n }\r\n if (prefix !== undefined && typeof prefix !== 'string') {\r\n throw new InvalidArgumentError('\"prefix\" must be a string when provided.')\r\n }\r\n\r\n const target = path.resolve(destDir)\r\n fs.mkdirSync(target, { recursive: true })\r\n\r\n // A buffer has to reach the disk for yauzl to read it; that copy is ours to\r\n // clean up, and it goes to the OS temp dir so it never pollutes `destDir`.\r\n let archivePath: string\r\n let scratchDir: string | null = null\r\n if (typeof source === 'string') {\r\n if (source.trim() === '') {\r\n throw new InvalidArgumentError('\"source\" must be a non-empty path.')\r\n }\r\n archivePath = path.resolve(source)\r\n if (!fs.existsSync(archivePath)) {\r\n throw new InvalidArgumentError(`Archive not found: ${archivePath}`)\r\n }\r\n } else if (source instanceof Uint8Array) {\r\n scratchDir = fs.mkdtempSync(path.join(os.tmpdir(), 'linea-core-archive-'))\r\n archivePath = path.join(scratchDir, 'archive.zip')\r\n fs.writeFileSync(archivePath, source)\r\n } else {\r\n throw new InvalidArgumentError('\"source\" must be a path or a Uint8Array.')\r\n }\r\n\r\n try {\r\n await extract(archivePath, { dir: target })\r\n } finally {\r\n if (scratchDir !== null) fs.rmSync(scratchDir, { recursive: true, force: true })\r\n }\r\n\r\n if (prefix === undefined) return { dir: target }\r\n\r\n const directories = fs\r\n .readdirSync(target, { withFileTypes: true })\r\n .filter((entry) => entry.isDirectory())\r\n .map((entry) => entry.name)\r\n .sort()\r\n\r\n // Same resolution as unZip: first match on the prefix, else the first\r\n // directory, else the extraction root itself.\r\n const chosen = directories.find((name) => name.startsWith(prefix)) ?? directories[0]\r\n return { dir: chosen === undefined ? target : path.join(target, chosen) }\r\n}\r\n"]}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A single file change between two directory trees.
|
|
3
|
+
*
|
|
4
|
+
* NEUTRAL FILE-CHANGE FORMAT. The field names (`action`, `file_path`,
|
|
5
|
+
* `content`, `encoding`) are GitLab's commit-action vocabulary, kept on purpose
|
|
6
|
+
* so linea-server can hand the array straight to `gitlabSession.commit` with no
|
|
7
|
+
* adapter in between. linea-core itself neither knows nor cares about GitLab
|
|
8
|
+
* (ADR-003) — this is a data shape, not a dependency.
|
|
9
|
+
*/
|
|
10
|
+
export interface FileChange {
|
|
11
|
+
readonly action: 'create' | 'update' | 'delete';
|
|
12
|
+
/** Path relative to the compared directory, ALWAYS POSIX (`/`). */
|
|
13
|
+
readonly file_path: string;
|
|
14
|
+
/** Absent for `delete`. */
|
|
15
|
+
readonly content?: string;
|
|
16
|
+
/** Absent for `delete`. */
|
|
17
|
+
readonly encoding?: 'text' | 'base64';
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Compares two directory trees and reports the changes needed to turn the old
|
|
21
|
+
* one into the new one.
|
|
22
|
+
*
|
|
23
|
+
* Preserves the monolith's three rules exactly:
|
|
24
|
+
* - present only in `oldDir` -> `delete`, EXCEPT `README.md`, never deleted.
|
|
25
|
+
* - present only in `newDir` -> `create`.
|
|
26
|
+
* - present in both with different bytes -> `update`.
|
|
27
|
+
* - present in both with the same bytes -> nothing.
|
|
28
|
+
*
|
|
29
|
+
* Binary files are read as base64 with `encoding: 'base64'`; text as UTF-8 with
|
|
30
|
+
* `encoding: 'text'`.
|
|
31
|
+
*
|
|
32
|
+
* @param params.oldDir Directory with the previous state.
|
|
33
|
+
* @param params.newDir Directory with the desired state.
|
|
34
|
+
* @returns The changes, sorted by `file_path` so the result is deterministic.
|
|
35
|
+
* @throws {InvalidArgumentError} when either path is not a non-empty string.
|
|
36
|
+
*/
|
|
37
|
+
export declare const diffDirectories: ({ oldDir, newDir }: {
|
|
38
|
+
oldDir: string;
|
|
39
|
+
newDir: string;
|
|
40
|
+
}) => FileChange[];
|
package/dist/fs/diff.js
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Directory comparison expressed as file changes.
|
|
3
|
+
*
|
|
4
|
+
* Migrated from `linea/server/src/model/services/utils.js` (~86-128):
|
|
5
|
+
* `isFileToDelete`, `isFileToCreate`, `isFileToUpdate`, `generateAction` and
|
|
6
|
+
* `generateActions`.
|
|
7
|
+
*
|
|
8
|
+
* Behaviour is preserved exactly; the IMPLEMENTATION is rebuilt (see below).
|
|
9
|
+
*/
|
|
10
|
+
import crypto from 'node:crypto';
|
|
11
|
+
import fs from 'node:fs';
|
|
12
|
+
import path from 'node:path';
|
|
13
|
+
import { InvalidArgumentError } from '../errors.js';
|
|
14
|
+
/**
|
|
15
|
+
* Files never reported as deleted.
|
|
16
|
+
*
|
|
17
|
+
* Verbatim from `isFileToDelete`, which excludes `README.md`: a generated
|
|
18
|
+
* product's README is written by hand and must survive a regeneration that no
|
|
19
|
+
* longer produces one.
|
|
20
|
+
*/
|
|
21
|
+
const NEVER_DELETED = new Set(['README.md']);
|
|
22
|
+
/**
|
|
23
|
+
* Extensions treated as binary.
|
|
24
|
+
*
|
|
25
|
+
* The monolith delegates to the `is-binary-path` package. Reproduced here as an
|
|
26
|
+
* explicit list to avoid a dependency whose only job is a lookup table, and
|
|
27
|
+
* because being explicit about what ends up base64-encoded is worth more than
|
|
28
|
+
* exhaustiveness. Content sniffing is deliberately avoided: it would make the
|
|
29
|
+
* encoding of a file depend on its bytes rather than its name, so the same file
|
|
30
|
+
* could change encoding between two runs.
|
|
31
|
+
*
|
|
32
|
+
* When in doubt, ADD the extension. The two mistakes are not symmetric: a false
|
|
33
|
+
* positive only base64-encodes a text file that did not need it, while a false
|
|
34
|
+
* negative reads binary content with `utf-8`, turns every invalid sequence into
|
|
35
|
+
* U+FFFD and commits a silently corrupted file to GitLab — no error, no warning.
|
|
36
|
+
*/
|
|
37
|
+
const BINARY_EXTENSIONS = new Set([
|
|
38
|
+
'.png', '.jpg', '.jpeg', '.gif', '.bmp', '.ico', '.webp', '.tif', '.tiff', '.avif',
|
|
39
|
+
'.svgz',
|
|
40
|
+
'.pdf', '.zip', '.gz', '.tar', '.tgz', '.bz2', '.7z', '.rar', '.jar', '.war',
|
|
41
|
+
'.woff', '.woff2', '.ttf', '.otf', '.eot',
|
|
42
|
+
'.mp3', '.mp4', '.avi', '.mov', '.webm', '.ogg', '.wav', '.flac',
|
|
43
|
+
'.so', '.dll', '.dylib', '.exe', '.class', '.pyc', '.wasm', '.node',
|
|
44
|
+
'.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx', '.odt', '.ods',
|
|
45
|
+
'.db', '.sqlite', '.keystore', '.jks', '.p12', '.pfx',
|
|
46
|
+
'.bin', '.dat'
|
|
47
|
+
]);
|
|
48
|
+
const isBinaryPath = (filePath) => BINARY_EXTENSIONS.has(path.extname(filePath).toLowerCase());
|
|
49
|
+
/**
|
|
50
|
+
* Repository-relative POSIX path of `filePath` inside `baseDir`.
|
|
51
|
+
*
|
|
52
|
+
* HARDENED PORT. `generateAction` derived this by splitting the absolute path on
|
|
53
|
+
* the literal `` `tmp${sep}${uuid}${sep}new` `` and keeping the tail — coupled to
|
|
54
|
+
* `properties.paths.output`, to the uuid-named temp layout, and silently wrong
|
|
55
|
+
* if any of that changed.
|
|
56
|
+
*
|
|
57
|
+
* It also had a LATENT BUG on Windows: `path.join` produces `\` separators, so
|
|
58
|
+
* `file_path` would come out as `src\main\App.java`, which the GitLab API
|
|
59
|
+
* rejects. The monolith never hit it because it only ever ran on Linux. Closed
|
|
60
|
+
* here by normalising to POSIX unconditionally.
|
|
61
|
+
*/
|
|
62
|
+
const toRepositoryPath = (baseDir, filePath) => path.relative(baseDir, filePath).split(path.sep).join('/');
|
|
63
|
+
/** Streaming MD5 of a file. Replaces `md5File.sync` from the monolith. */
|
|
64
|
+
const md5 = (filePath) => {
|
|
65
|
+
const hash = crypto.createHash('md5');
|
|
66
|
+
hash.update(fs.readFileSync(filePath));
|
|
67
|
+
return hash.digest('hex');
|
|
68
|
+
};
|
|
69
|
+
/** Same bytes on both sides? Compared by digest, as the monolith does. */
|
|
70
|
+
const hasSameContent = (a, b) => md5(a) === md5(b);
|
|
71
|
+
const readAsChange = (action, baseDir, absolutePath) => {
|
|
72
|
+
const binary = isBinaryPath(absolutePath);
|
|
73
|
+
return {
|
|
74
|
+
action,
|
|
75
|
+
file_path: toRepositoryPath(baseDir, absolutePath),
|
|
76
|
+
content: fs.readFileSync(absolutePath, binary ? 'base64' : 'utf-8'),
|
|
77
|
+
encoding: binary ? 'base64' : 'text'
|
|
78
|
+
};
|
|
79
|
+
};
|
|
80
|
+
/** Relative POSIX paths of every file under `dir`, recursively. */
|
|
81
|
+
const listFiles = (dir) => {
|
|
82
|
+
const found = [];
|
|
83
|
+
const walk = (current, prefix) => {
|
|
84
|
+
let entries;
|
|
85
|
+
try {
|
|
86
|
+
entries = fs.readdirSync(current, { withFileTypes: true });
|
|
87
|
+
}
|
|
88
|
+
catch {
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
for (const entry of entries) {
|
|
92
|
+
const relative = prefix === '' ? entry.name : `${prefix}/${entry.name}`;
|
|
93
|
+
if (entry.isDirectory()) {
|
|
94
|
+
walk(path.join(current, entry.name), relative);
|
|
95
|
+
}
|
|
96
|
+
else if (entry.isFile()) {
|
|
97
|
+
found.push(relative);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
};
|
|
101
|
+
walk(dir, '');
|
|
102
|
+
return found.sort();
|
|
103
|
+
};
|
|
104
|
+
const assertDir = (value, parameter) => {
|
|
105
|
+
if (typeof value !== 'string' || value.trim() === '') {
|
|
106
|
+
throw new InvalidArgumentError(`"${parameter}" must be a non-empty path.`);
|
|
107
|
+
}
|
|
108
|
+
return path.resolve(value);
|
|
109
|
+
};
|
|
110
|
+
/**
|
|
111
|
+
* Compares two directory trees and reports the changes needed to turn the old
|
|
112
|
+
* one into the new one.
|
|
113
|
+
*
|
|
114
|
+
* Preserves the monolith's three rules exactly:
|
|
115
|
+
* - present only in `oldDir` -> `delete`, EXCEPT `README.md`, never deleted.
|
|
116
|
+
* - present only in `newDir` -> `create`.
|
|
117
|
+
* - present in both with different bytes -> `update`.
|
|
118
|
+
* - present in both with the same bytes -> nothing.
|
|
119
|
+
*
|
|
120
|
+
* Binary files are read as base64 with `encoding: 'base64'`; text as UTF-8 with
|
|
121
|
+
* `encoding: 'text'`.
|
|
122
|
+
*
|
|
123
|
+
* @param params.oldDir Directory with the previous state.
|
|
124
|
+
* @param params.newDir Directory with the desired state.
|
|
125
|
+
* @returns The changes, sorted by `file_path` so the result is deterministic.
|
|
126
|
+
* @throws {InvalidArgumentError} when either path is not a non-empty string.
|
|
127
|
+
*/
|
|
128
|
+
export const diffDirectories = ({ oldDir, newDir }) => {
|
|
129
|
+
const oldRoot = assertDir(oldDir, 'oldDir');
|
|
130
|
+
const newRoot = assertDir(newDir, 'newDir');
|
|
131
|
+
const oldFiles = new Set(listFiles(oldRoot));
|
|
132
|
+
const newFiles = listFiles(newRoot);
|
|
133
|
+
const changes = [];
|
|
134
|
+
for (const relative of newFiles) {
|
|
135
|
+
const newPath = path.join(newRoot, ...relative.split('/'));
|
|
136
|
+
if (!oldFiles.has(relative)) {
|
|
137
|
+
changes.push(readAsChange('create', newRoot, newPath));
|
|
138
|
+
continue;
|
|
139
|
+
}
|
|
140
|
+
const oldPath = path.join(oldRoot, ...relative.split('/'));
|
|
141
|
+
if (!hasSameContent(oldPath, newPath)) {
|
|
142
|
+
changes.push(readAsChange('update', newRoot, newPath));
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
const newFileSet = new Set(newFiles);
|
|
146
|
+
for (const relative of oldFiles) {
|
|
147
|
+
if (newFileSet.has(relative))
|
|
148
|
+
continue;
|
|
149
|
+
if (NEVER_DELETED.has(path.posix.basename(relative)))
|
|
150
|
+
continue;
|
|
151
|
+
changes.push({ action: 'delete', file_path: relative });
|
|
152
|
+
}
|
|
153
|
+
return changes.sort((a, b) => (a.file_path < b.file_path ? -1 : a.file_path > b.file_path ? 1 : 0));
|
|
154
|
+
};
|
|
155
|
+
//# sourceMappingURL=diff.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"diff.js","sourceRoot":"","sources":["../../src/fs/diff.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,MAAM,MAAM,aAAa,CAAA;AAChC,OAAO,EAAE,MAAM,SAAS,CAAA;AACxB,OAAO,IAAI,MAAM,WAAW,CAAA;AAC5B,OAAO,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAA;AAqBnD;;;;;;GAMG;AACH,MAAM,aAAa,GAAG,IAAI,GAAG,CAAC,CAAC,WAAW,CAAC,CAAC,CAAA;AAE5C;;;;;;;;;;;;;;GAcG;AACH,MAAM,iBAAiB,GAAG,IAAI,GAAG,CAAC;IAChC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO;IAClF,OAAO;IACP,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM;IAC5E,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM;IACzC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO;IAChE,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,QAAQ,EAAE,M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CAAC,IAAI,CAAC,YAAY,CAAC,QAAQ,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC,CAAA;QACxD,CAAC;IACH,CAAC;IAED,MAAM,UAAU,GAAG,IAAI,GAAG,CAAC,QAAQ,CAAC,CAAA;IACpC,KAAK,MAAM,QAAQ,IAAI,QAAQ,EAAE,CAAC;QAChC,IAAI,UAAU,CAAC,GAAG,CAAC,QAAQ,CAAC;YAAE,SAAQ;QACtC,IAAI,aAAa,CAAC,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;YAAE,SAAQ;QAC9D,OAAO,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,QAAQ,EAAE,SAAS,EAAE,QAAQ,EAAE,CAAC,CAAA;IACzD,CAAC;IAED,OAAO,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,SAAS,GAAG,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,GAAG,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;AACrG,CAAC,CAAA","sourcesContent":["/**\r\n * Directory comparison expressed as file changes.\r\n *\r\n * Migrated from `linea/server/src/model/services/utils.js` (~86-128):\r\n * `isFileToDelete`, `isFileToCreate`, `isFileToUpdate`, `generateAction` and\r\n * `generateActions`.\r\n *\r\n * Behaviour is preserved exactly; the IMPLEMENTATION is rebuilt (see below).\r\n */\r\nimport crypto from 'node:crypto'\r\nimport fs from 'node:fs'\r\nimport path from 'node:path'\r\nimport { InvalidArgumentError } from '../errors.js'\r\n\r\n/**\r\n * A single file change between two directory trees.\r\n *\r\n * NEUTRAL FILE-CHANGE FORMAT. The field names (`action`, `file_path`,\r\n * `content`, `encoding`) are GitLab's commit-action vocabulary, kept on purpose\r\n * so linea-server can hand the array straight to `gitlabSession.commit` with no\r\n * adapter in between. linea-core itself neither knows nor cares about GitLab\r\n * (ADR-003) — this is a data shape, not a dependency.\r\n */\r\nexport interface FileChange {\r\n readonly action: 'create' | 'update' | 'delete'\r\n /** Path relative to the compared directory, ALWAYS POSIX (`/`). */\r\n readonly file_path: string\r\n /** Absent for `delete`. */\r\n readonly content?: string\r\n /** Absent for `delete`. */\r\n readonly encoding?: 'text' | 'base64'\r\n}\r\n\r\n/**\r\n * Files never reported as deleted.\r\n *\r\n * Verbatim from `isFileToDelete`, which excludes `README.md`: a generated\r\n * product's README is written by hand and must survive a regeneration that no\r\n * longer produces one.\r\n */\r\nconst NEVER_DELETED = new Set(['README.md'])\r\n\r\n/**\r\n * Extensions treated as binary.\r\n *\r\n * The monolith delegates to the `is-binary-path` package. Reproduced here as an\r\n * explicit list to avoid a dependency whose only job is a lookup table, and\r\n * because being explicit about what ends up base64-encoded is worth more than\r\n * exhaustiveness. Content sniffing is deliberately avoided: it would make the\r\n * encoding of a file depend on its bytes rather than its name, so the same file\r\n * could change encoding between two runs.\r\n *\r\n * When in doubt, ADD the extension. The two mistakes are not symmetric: a false\r\n * positive only base64-encodes a text file that did not need it, while a false\r\n * negative reads binary content with `utf-8`, turns every invalid sequence into\r\n * U+FFFD and commits a silently corrupted file to GitLab — no error, no warning.\r\n */\r\nconst BINARY_EXTENSIONS = new Set([\r\n '.png', '.jpg', '.jpeg', '.gif', '.bmp', '.ico', '.webp', '.tif', '.tiff', '.avif',\r\n '.svgz',\r\n '.pdf', '.zip', '.gz', '.tar', '.tgz', '.bz2', '.7z', '.rar', '.jar', '.war',\r\n '.woff', '.woff2', '.ttf', '.otf', '.eot',\r\n '.mp3', '.mp4', '.avi', '.mov', '.webm', '.ogg', '.wav', '.flac',\r\n '.so', '.dll', '.dylib', '.exe', '.class', '.pyc', '.wasm', '.node',\r\n '.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx', '.odt', '.ods',\r\n '.db', '.sqlite', '.keystore', '.jks', '.p12', '.pfx',\r\n '.bin', '.dat'\r\n])\r\n\r\nconst isBinaryPath = (filePath: string): boolean =>\r\n BINARY_EXTENSIONS.has(path.extname(filePath).toLowerCase())\r\n\r\n/**\r\n * Repository-relative POSIX path of `filePath` inside `baseDir`.\r\n *\r\n * HARDENED PORT. `generateAction` derived this by splitting the absolute path on\r\n * the literal `` `tmp${sep}${uuid}${sep}new` `` and keeping the tail — coupled to\r\n * `properties.paths.output`, to the uuid-named temp layout, and silently wrong\r\n * if any of that changed.\r\n *\r\n * It also had a LATENT BUG on Windows: `path.join` produces `\\` separators, so\r\n * `file_path` would come out as `src\\main\\App.java`, which the GitLab API\r\n * rejects. The monolith never hit it because it only ever ran on Linux. Closed\r\n * here by normalising to POSIX unconditionally.\r\n */\r\nconst toRepositoryPath = (baseDir: string, filePath: string): string =>\r\n path.relative(baseDir, filePath).split(path.sep).join('/')\r\n\r\n/** Streaming MD5 of a file. Replaces `md5File.sync` from the monolith. */\r\nconst md5 = (filePath: string): string => {\r\n const hash = crypto.createHash('md5')\r\n hash.update(fs.readFileSync(filePath))\r\n return hash.digest('hex')\r\n}\r\n\r\n/** Same bytes on both sides? Compared by digest, as the monolith does. */\r\nconst hasSameContent = (a: string, b: string): boolean => md5(a) === md5(b)\r\n\r\nconst readAsChange = (\r\n action: 'create' | 'update',\r\n baseDir: string,\r\n absolutePath: string\r\n): FileChange => {\r\n const binary = isBinaryPath(absolutePath)\r\n return {\r\n action,\r\n file_path: toRepositoryPath(baseDir, absolutePath),\r\n content: fs.readFileSync(absolutePath, binary ? 'base64' : 'utf-8'),\r\n encoding: binary ? 'base64' : 'text'\r\n }\r\n}\r\n\r\n/** Relative POSIX paths of every file under `dir`, recursively. */\r\nconst listFiles = (dir: string): string[] => {\r\n const found: string[] = []\r\n const walk = (current: string, prefix: string): void => {\r\n let entries: fs.Dirent[]\r\n try {\r\n entries = fs.readdirSync(current, { withFileTypes: true })\r\n } catch {\r\n return\r\n }\r\n for (const entry of entries) {\r\n const relative = prefix === '' ? entry.name : `${prefix}/${entry.name}`\r\n if (entry.isDirectory()) {\r\n walk(path.join(current, entry.name), relative)\r\n } else if (entry.isFile()) {\r\n found.push(relative)\r\n }\r\n }\r\n }\r\n walk(dir, '')\r\n return found.sort()\r\n}\r\n\r\nconst assertDir = (value: unknown, parameter: string): string => {\r\n if (typeof value !== 'string' || value.trim() === '') {\r\n throw new InvalidArgumentError(`\"${parameter}\" must be a non-empty path.`)\r\n }\r\n return path.resolve(value)\r\n}\r\n\r\n/**\r\n * Compares two directory trees and reports the changes needed to turn the old\r\n * one into the new one.\r\n *\r\n * Preserves the monolith's three rules exactly:\r\n * - present only in `oldDir` -> `delete`, EXCEPT `README.md`, never deleted.\r\n * - present only in `newDir` -> `create`.\r\n * - present in both with different bytes -> `update`.\r\n * - present in both with the same bytes -> nothing.\r\n *\r\n * Binary files are read as base64 with `encoding: 'base64'`; text as UTF-8 with\r\n * `encoding: 'text'`.\r\n *\r\n * @param params.oldDir Directory with the previous state.\r\n * @param params.newDir Directory with the desired state.\r\n * @returns The changes, sorted by `file_path` so the result is deterministic.\r\n * @throws {InvalidArgumentError} when either path is not a non-empty string.\r\n */\r\nexport const diffDirectories = ({\r\n oldDir,\r\n newDir\r\n}: {\r\n oldDir: string\r\n newDir: string\r\n}): FileChange[] => {\r\n const oldRoot = assertDir(oldDir, 'oldDir')\r\n const newRoot = assertDir(newDir, 'newDir')\r\n\r\n const oldFiles = new Set(listFiles(oldRoot))\r\n const newFiles = listFiles(newRoot)\r\n const changes: FileChange[] = []\r\n\r\n for (const relative of newFiles) {\r\n const newPath = path.join(newRoot, ...relative.split('/'))\r\n if (!oldFiles.has(relative)) {\r\n changes.push(readAsChange('create', newRoot, newPath))\r\n continue\r\n }\r\n const oldPath = path.join(oldRoot, ...relative.split('/'))\r\n if (!hasSameContent(oldPath, newPath)) {\r\n changes.push(readAsChange('update', newRoot, newPath))\r\n }\r\n }\r\n\r\n const newFileSet = new Set(newFiles)\r\n for (const relative of oldFiles) {\r\n if (newFileSet.has(relative)) continue\r\n if (NEVER_DELETED.has(path.posix.basename(relative))) continue\r\n changes.push({ action: 'delete', file_path: relative })\r\n }\r\n\r\n return changes.sort((a, b) => (a.file_path < b.file_path ? -1 : a.file_path > b.file_path ? 1 : 0))\r\n}\r\n"]}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Formats every file prettier understands under a directory, in place.
|
|
3
|
+
*
|
|
4
|
+
* Files with no inferable parser are skipped, which is what `--ignore-unknown`
|
|
5
|
+
* does. Files that prettier cannot parse (a syntax error in generated code, say)
|
|
6
|
+
* are skipped too rather than aborting the whole run: formatting is cosmetic and
|
|
7
|
+
* must never fail a generation.
|
|
8
|
+
*
|
|
9
|
+
* Idempotent by construction, since prettier output is a fixed point. A file is
|
|
10
|
+
* only rewritten when its content actually changes, so mtimes stay put and the
|
|
11
|
+
* directory diff does not gain spurious entries.
|
|
12
|
+
*
|
|
13
|
+
* @param params.dir Directory to format, in place.
|
|
14
|
+
* @returns How many files were rewritten.
|
|
15
|
+
* @throws {InvalidArgumentError} when `dir` is not a non-empty existing directory.
|
|
16
|
+
*/
|
|
17
|
+
export declare const formatDirectory: ({ dir }: {
|
|
18
|
+
dir: string;
|
|
19
|
+
}) => Promise<{
|
|
20
|
+
formatted: number;
|
|
21
|
+
}>;
|