From d5b5c2e13940b49c467021f9df07e1b6e7d2a363 Mon Sep 17 00:00:00 2001 From: Pawel Wolanski Date: Sat, 21 Nov 2026 01:44:22 +0100 Subject: [PATCH 01/25] docs(impex): add editor migration plan --- docs/dev/impex/editor-replacement-plan.md | 268 +++++ docs/dev/impex/impex-docs.md | 1122 +++++++++++++++++++++ docs/dev/impex/impex.tmLanguage.json | 87 ++ 3 files changed, 1477 insertions(+) create mode 100644 docs/dev/impex/editor-replacement-plan.md create mode 100644 docs/dev/impex/impex-docs.md create mode 100644 docs/dev/impex/impex.tmLanguage.json diff --git a/docs/dev/impex/editor-replacement-plan.md b/docs/dev/impex/editor-replacement-plan.md new file mode 100644 index 00000000..57733c3b --- /dev/null +++ b/docs/dev/impex/editor-replacement-plan.md @@ -0,0 +1,268 @@ +# ImpEx editor replacement plan + +Status: proposed; no production editor or build changes made. + +## Goal and scope + +Replace the custom `com.hybris.hyeclipse.impexed` editor with Eclipse's Generic +Editor, TM4E syntax highlighting, and LSP4E-backed language services. Formatting, +type-system completion, and the new-file wizard are mandatory replacement +features. Highlighting-only builds are opt-in previews, not the completed +replacement; retire the legacy editor only after these features pass acceptance +tests and the remaining migration decisions are resolved. + +Inputs: + +- [ImpEx behavior notes](impex-docs.md): reference for lexical edge cases, not a + complete formal language specification. Runtime-dependent claims require + verification against the supported Commerce version. +- [TextMate grammar](impex.tmLanguage.json): starting point, not production-ready. +- Existing `com.hybris.hyeclipse.impexed/plugin.xml`, editor, wizard, formatter, + completion processors, and hyperlink classes. + +## Architecture + +```text +.impex file -> ImpEx content type -> Eclipse Generic Editor + |-> TM4E: TextMate scopes and theme colors + |-> LSP4E: document synchronization/services + |-> ImpEx language server +``` + +TextMate grammars are not LSP servers. TM4E provides immediate lexical +highlighting; LSP4E is the client for a separately implemented server. LSP +semantic tokens can enrich highlighting later, but are unnecessary for the +first milestone. Do not create an empty server just to enable coloring. + +Proposed modules: + +- `com.hybris.hyeclipse.impex`: Eclipse content-type/editor registration, + packaged grammar, language configuration, wizard, and eventual LSP4E binding. +- `com.hybris.hyeclipse.impex.ls`: non-UI Java language server using LSP4J, + introduced when useful language services are implemented. +- `com.hybris.hyeclipse.impex.tests`: grammar, protocol, and Eclipse integration + tests; not a fragment of the importer bundle. + +Start with an in-process server connection, provided the target LSP4E APIs +support it cleanly. Keep Eclipse UI/resource adapters outside the server's +language logic. Defer a standalone server distribution and external process +management unless required by other clients. + +Use dependencies from p2 and manifest declarations. Verify Generic Editor, +TM4E, LSP4E, and LSP4J versions available in Eclipse 2026-09 before choosing +exact APIs. If additional repositories are needed, use compatible versioned +release sites rather than floating snapshots/latest sites. Ensure the delivered +p2 feature resolves these dependencies, not just the development target. + +## Grammar corrections + +The current grammar starts a string on any quote, treats `\\.` as an escape, +recognizes only unquoted `#` comments, and cannot distinguish scripts from +comments. Correct these before editor cutover: + +- Model cell boundaries and quoted multiline cells; quoting starts at the + beginning of a cell, allowing leading whitespace as verified by fixtures. +- Use doubled `""` for escaped quotes. A backslash does not escape a quote. +- Separate trailing-backslash continuation from quoted multiline values. +- Recognize first-cell comments, including quoted first cells starting with + `#`; keep `#` in later cells as ordinary data. +- Match quoted/unquoted `#%` script directives before general comments; + distinguish engine tags and hooks such as `if:`, `endif:`, and `beforeEach:`. + Do not execute scripts or promise full embedded-language validation. +- Highlight operation headers, type names, column attributes, nested reference + paths, header/column modifiers, macro definitions/references, document IDs, + special columns, ``, ``, and collection prefixes `(+)/(-)/(+?)`. +- Treat `` as a token, not a universal null assignment. Do not label + unknown macros or configurable header shorthands as errors by default. +- Use standard theme scopes, preserving `text.tabular.impex` unless compatibility + testing identifies a reason to change it. Color booleans/numbers contextually, + avoiding false matches inside identifiers or arbitrary data. + +TextMate is a lexical approximation, not the import parser. Document unsupported +contexts instead of using increasingly fragile regexes to simulate execution. +Choose one canonical grammar location when packaging; do not maintain two +independently edited copies in documentation and the bundle. + +## Delivery phases + +### 1. Dependency and migration spike + +- Resolve target bundles and inspect their extension schemas. +- Register an ImpEx content type derived from text and map `.impex` files to it. +- Prove Generic Editor + TM4E highlighting in a minimal installable feature. +- Verify light/dark themes and opening files outside a Commerce project. +- Audit all references to the old bundle, editor ID, command IDs, and preferences. + The existing new-file wizard explicitly targets the old editor ID via a marker. +- Capture representative fixtures from the supplied notes and real project files. + +Exit: a working editor integration and a documented dependency/migration matrix. + +### 2. Highlighting release (opt-in) + +- Implement and test the grammar corrections above with TM4E token-scope tests. +- Package grammar/configuration resources via `build.properties`. +- Add the new bundle to root `pom.xml` and the installable feature. +- Keep the old editor available through **Open With**; avoid competing default + registrations and global formatter shortcuts. +- Implement the new-file wizard described below. New files must open in the + Generic Editor, not target the old editor ID. + +Exit: reliable highlighting with no server, no required Commerce installation, +and an explicit user-visible list of remaining legacy-only features. + +### 3. Required language services and formatting + +- Implement server initialization/shutdown and open/change/close synchronization. + Start with full document synchronization; optimize only after measurement. +- Add macro/header document symbols and macro completion/hover as initial services. +- Add conservative lexical diagnostics (for example, unmatched cell quotes) using + source ranges from a dedicated cell-aware scanner, not TextMate scopes alone. +- Ignore stale results after edits; bound background work and clean up documents + and connections on close/shutdown. Advertise only implemented capabilities. +- Implement type-system completion and navigation using the shared + `TypeSystemSnapshot`, as specified below. +- Implement document/range formatting using the same cell-aware scanner and + the safety rules below; wire the Eclipse formatting action through LSP4E. + +Exit: formatting, type-system completion, and navigation pass acceptance tests. +Highlighting still works if language services fail or the Commerce type index +is unavailable; the wizard remains usable without a server. + +### 4. Cutover and legacy retirement + +Require the three features below and resolve the remaining migration decisions +before changing the default editor: + +| Legacy behavior | Replacement policy | +| --- | --- | +| Syntax coloring and color preferences | TM4E grammar and theme preferences | +| New ImpEx wizard/shortcut | Required: validated creation and Generic Editor routing | +| Type/attribute completion | Required: context-sensitive LSP completion using the shared type index | +| Type hyperlinks | LSP definition locations | +| Formatting (`M1+Shift+F`) | Required: safe document/range formatting and undo/redo | +| Custom auto-edit/comment behavior | TM4E language configuration where safe; verify against data cells | +| Old editor IDs/preferences | Document reassociation and preference changes; migrate only with explicit policy | + +Remove the old editor from the main feature/reactor only after parity decisions +and upgrade tests pass. Test upgrades from an existing installation: dropping a +bundle from a feature does not by itself prove old associations or installed +bundles disappear. Keep a temporary opt-in legacy feature if gaps require it. +Do not delete the old source or published update-site history during the spike. + +## Required feature specifications + +### Formatting + +- Provide LSP `textDocument/formatting` and `textDocument/rangeFormatting`. + Preserve the existing **Format ImpEx** workflow, context-menu entry, and + `M1+Shift+F`, scoped to the ImpEx editor without conflicting with other editors. +- Align semicolon-separated header/data columns within each header block using + whitespace only at verified safe cell boundaries. Honor supported LSP + formatting options and document any fixed alignment policy. +- Use a scanner that preserves raw cell text, quoting, physical line boundaries, + and continuation state. The old `Formatter`/`LineData` behavior is a comparison + baseline, not a parser to copy unchanged. +- Never reorder rows/columns, add/remove cells, expand macros, normalize values, + rewrite scripts, or change ``, ``, collection prefixes, or modifiers. + Preserve empty/trailing cells, quote doubling, line endings, final-newline state, + comments, script lines, and macro definitions. +- Leave multiline quoted records and backslash-continuation records unchanged + unless a tested transformation proves their values are preserved. For malformed + or ambiguous input, return no edits for affected blocks rather than guessing. +- Range formatting changes only complete, safely parseable blocks contained in + the selection; otherwise return no edits. Width calculations must not cause + changes outside the selected range. +- Return non-overlapping `TextEdit`s against the analyzed document version. + Applying formatting must be one undoable editor operation and be idempotent. + +Acceptance: golden-output tests for aligned blocks; parse-before/after checks for +equivalent cell values and structure; explicit unchanged-output tests for scripts, +multiline/continued records, and invalid input; range isolation, Unicode, CRLF/LF, +idempotence, and editor undo/redo. Use the documented ImpEx lexical rules, not an +RFC 4180 CSV parser, for equivalence checks. + +### Type-system completion and navigation + +- Provide context-sensitive LSP `textDocument/completion` for type names after + operation keywords, attributes after header separators, and reference attributes + inside nested paths such as `catalogVersion(catalog(id),version)`. +- Reuse the shared type-system index exposed through the commons bundle and + `TypeSystemSnapshot`; avoid duplicate indexing and dependencies on the legacy + editor's `Activator`. Include inherited attributes when exposed by the index. +- Add modifier-name/value proposals in the correct header/column context, alongside + macro and operation proposals. Filter by the typed prefix and replace only the + current token using precise edit ranges, including partially typed headers. +- Supply useful type/attribute details from indexed metadata, without promising + runtime database validation. Add type definition navigation and attribute + navigation where source locations are available. +- Bridge workspace/project-scoped immutable metadata into server services through + an adapter. Verify whether the existing index supports project isolation; if it + does not, address that before enabling completion across multiple Commerce roots. +- Refresh proposals after index rebuilds without blocking the UI. With a missing + index or unknown type, retain syntax/macro/modifier proposals and return no + speculative attributes; do not mark valid project-dependent names as errors. + +Acceptance: type, inherited attribute, nested-reference, modifier, and macro +proposals; prefix filtering and replacement ranges; partial documents; no attribute +proposals in ordinary data/comments; index refresh; missing index; two projects with +different types; definition locations and no legacy-editor dependencies. + +### New-file wizard + +- Register **File > New > Other > SAP > New ImpEx File** in the new Eclipse bundle, + retaining the existing `M1+Shift+Y` workflow. Reuse standard Eclipse new-file + wizard/page APIs rather than rebuilding generic container/file validation. +- Preselect the project/folder from the current selection, including adaptable + Java package selections; allow browsing and use `test.impex` as the initial + filename for compatibility. Create the file in a writable workspace container. +- Validate names, accessible containers, and existing files. Never silently + overwrite an existing file (the old wizard currently does so). +- Create a minimal starter comment explaining content assist, with explicit + encoding and the project's line-ending convention; reveal the file and open it + in the Generic Editor so highlighting and language services attach normally. +- Work without a Commerce installation, type index, or running language server. + Perform file operations with workspace scheduling/progress support and open the + editor on the display thread. External-file creation is outside wizard scope. +- Localize labels/errors and preserve or alias the old wizard command ID only + when its registration is removed from the old bundle: avoid duplicate commands + and shortcuts during coexistence. +- The old page also accepts `.csv`. Preserve explicit `.csv` creation, but do not + globally associate all CSV files with ImpEx. Open wizard-created ImpEx CSV files + explicitly in the Generic Editor with the ImpEx content-type override, if the + target APIs support it; otherwise document that compatibility gap for approval. + +Acceptance: project/folder/Java selection, browsing, filename and duplicate-file +validation, read-only/closed projects, cancellation, encoding, starter content, +editor opening, shortcut/command routing, and operation without language services. + +## Validation and release gates + +- Token fixtures: doubled and mid-cell quotes, quoted multiline cells, malformed + quotes, backslash continuation, CRLF/LF, quoted comments/scripts, later-cell + `#`, macros, nested references, modifiers, special values, and collection prefixes. +- Editor tests: content-type registration, new/open/save/save-as, wizard routing, + Unicode, external files, themes, and old workspace/file associations. +- LSP tests: lifecycle, edits/positions (UTF-16), stale diagnostics, completion, + cancellation where supported, and multiple projects with different type systems. +- Required feature gates: all formatting, completion/navigation, and wizard + acceptance cases above pass before legacy-editor retirement. +- Performance: benchmark large generated `.impex` files and long unterminated + quoted cells; set latency/memory budgets from baseline measurements. +- Run `make test` and `make package`; install the produced p2 ZIP in a clean + Eclipse 2026-09 instance and an upgraded existing installation. +- Never execute ImpEx scripts, import data, resolve server files, or access a + database as part of highlighting or language analysis. + +## Decisions needed + +1. Should the opt-in highlighting preview be published before feature completion? +2. Which additional legacy behaviors must be preserved beyond the required features? +3. Is a reusable standalone language server required, or only Eclipse integration? + +Recommended defaults: opt-in highlighting preview first; wizard, formatting, +type-system completion, and navigation before retirement; defer standalone +distribution. Implementation effort should be estimated after the dependency +spike and any additional parity requirements are agreed. + +References: [TM4E](https://github.com/eclipse-tm4e/tm4e), +[LSP4E](https://github.com/eclipse-lsp4e/lsp4e). diff --git a/docs/dev/impex/impex-docs.md b/docs/dev/impex/impex-docs.md new file mode 100644 index 00000000..8b17abe6 --- /dev/null +++ b/docs/dev/impex/impex-docs.md @@ -0,0 +1,1122 @@ +## The ImpEx CSV parser +ImpEx reads a file with its own CSVReader. In 2016 I referred to RFC 4180 as the specification. That was a mistake: this parser has its own rules. + +Quotes don't protect spaces +A quoted value is trimmed at the edges exactly like an unquoted one: + + +Example. + +```impex +INSERT_UPDATE TestItemType2;foo[unique=true];bar +;ih-a1;" padded " +``` + +``` +[ih-a1] bar=[padded] +``` +There is no way to import a value with leading or trailing spaces through ImpEx, except with a cell decorator or a translator that adds them back. Spaces inside a multiline value are preserved: only the edges of the whole value are trimmed. + +### A quote starts quoting only at the beginning of a cell +In the middle of a value, a quote is an ordinary character: +```impex +;ih-a2;abc"def +``` + +``` +[ih-a2] bar=[abc"def] +``` + +But a non-whitespace character after the closing quote is an error: +```impex +;ih-a3;"abc"def +``` +result +``` +unexpected char d after cell end at 12 in line 1 : ';ih-a3;"abc"def' +``` + +People often trip over this with inches. A backslash in ImpEx does not escape a quote, so `"5\" monitor"` is the cell 5\, closed by a quote and followed by monitor: +``` +unexpected char m after cell end at 12 in line 2 : ';ih-b2;"5\" monitor' +``` + +A quote inside quotes is doubled: `"5"" monitor"`. + +### An unmatched quote and an error on the wrong line +If a line ends "inside quotes," the parser assumes the value continues and appends the next line. Then another one, until the quotes balance or the file ends. + +```groovy +// illustration +boolean isWrappedLine(String line, boolean alreadyQuoted) { + boolean quoted = alreadyQuoted, cellStarted = alreadyQuoted, cellEnded = false; + for (char c : line) { + if (quoted) { + if (c == '"') { if (next == '"') skip(); else { quoted = false; cellEnded = true; } } + } else if (c == '"') { + if (cellEnded) throw new IllegalStateException("unexpected text separator ..."); + if (!cellStarted) { quoted = true; cellStarted = true; } // only at the start of a cell + } else if (c == ';') { + cellStarted = cellEnded = false; + } else if (!isWhitespace(c)) { + if (cellEnded) throw new IllegalStateException("unexpected char " + c + " after cell end ..."); + cellStarted = true; + } + } + return quoted; // true → glue the next line +} +``` + + +Illustrative reconstruction, not platform source code. See the note above. + +Example. Here the second data line is to blame, with an opening quote and no closing one: + +```impex +INSERT_UPDATE TestItemType2;foo[unique=true];bar +;ih-e1;ok +;ih-e2;"27 inch monitor +;ih-e3;fine +;ih-e4;"bold";x +;ih-e5;last +``` + +Result: +``` +[ih-e1] bar=[ok] +[ih-e5] bar=[last] +``` + +Three lines are gone, and the log says: +``` +unexpected char b after cell end at 8 in line 2 : ';ih-e4;"bold";x' +``` + +The line in the message, ;ih-e4;"bold";x, is correct. The error happened when the parser, gluing lines after ih-e2, reached the quote in ih-e4 and took it for a closing one. The number line 2 points to the real cause (ih-e2 is line 2 if you count from zero and include the header), while the text points to ih-e4. And ih-e3, which doesn't appear in the message at all, wasn't imported either. + +If there are no more quotes until the end of the file, the message is more accurate: + +``` +reached EOF and got odd number of '"'! File is corrupt. Error starts in line: +";ih-c2;"27 inch monitor" and occurs somewhere in the following lines. +``` + +If more than csv.maxmultilines lines get glued together (10,000 by default), the parser stops with a separate message. + +None of these errors are visible in HAC. The result block says "Import has encountered problems." and there is nothing below it. The error text is only in the server console log. + +### Line breaks and backslashes are two different mechanisms +Quotes preserve a line break inside a value: + +``` +;ih-a4;"line1 +line2" +``` +``` +[ih-a4] bar=[line1\nline2] +``` +A backslash at the end of a line joins it with the next one directly, with no space and no line break: + +``` +;ih-a5;part1\ +part2 +``` + +``` +[ih-a5] bar=[part1part2] +``` + + +This is a correction to the 2016 article. Back then I wrote that \ cannot be used as a multiline separator in a data block. On 2211 that is not true: in the example above, \ is in a data line, and the joining works. + +### A comment is determined by the first cell +A line is a comment if its first cell starts with #. So # in the middle of a line is ordinary data: + +``` +;ih-a7;value # not a comment +``` + +``` +[ih-a7] bar=[value # not a comment] + +``` + +But this is a comment, even though it looks like data: +``` +"# quoted comment?";ih-a7b;x +``` + +The check runs after the cell has been extracted from its quotes. So a quoted first cell that starts with # is also a comment. This is exactly why quoted code lines like "#% ...", described below, work. + +## An empty cell, , and + +How the three options behave on 2211: + +| In the cell | String attribute | Reference +|-----|--------|--------| +| empty | `null` is written | `null` is written | +| ``| the attribute is left untouched | the attribute is left untouched | +| `` | the string `` is written | it looks for an item whose key is `null` | + + +Example. + +```impex +INSERT_UPDATE TestItemType2;foo[unique=true];bar +;ih-m1;start +;ih-m2;start +;ih-m3;start +INSERT_UPDATE TestItemType2;foo[unique=true];bar +;ih-m1; +;ih-m2; +;ih-m3; +``` + +``` +[ih-m1] bar=[null] +[ih-m2] bar=[start] +[ih-m3] bar=[] +``` + +`` does what you expect. But `` is used for lookups in a reference. Try clearing a reference: + +```impex +INSERT_UPDATE Employee;uid[unique=true];sessionLanguage(isocode) +;ih-emp2; +``` +``` +column 2: cannot resolve value '' for attribute 'sessionLanguage' +``` +ImpEx looked for a language with isocode IS NULL and didn't find one. To clear a reference, you need an empty cell. + +`` is meant for composite keys where one of the parts is empty. For example, an address with no town: + +```impex +INSERT Address;owner(Employee.uid);streetname;town +;ih-emp1;ih-street; +;ih-emp1;ih-street;Berlin + +INSERT_UPDATE Employee;uid[unique=true];defaultShipmentAddress(streetname,town) +;ih-emp1;ih-street: +;ih-emp2;ih-street:Berlin +``` + +``` +ih-emp1 -> ih-street/null +ih-emp2 -> ih-street/Berlin +``` + + +Under the hood, the engine simply rewrites the query text: every =?parameter whose value turns out to be null is replaced with IS NULL. + +```groovy +// illustration +for (Map.Entry e : values.entrySet()) { + if (e.getValue() == null) { + query = query.replaceAll("=\\?" + e.getKey(), " IS NULL "); + } +} +``` + + +Illustrative reconstruction, not platform source code. See the note above. + +Case doesn't matter: `` works the same way. + +### Resolving references with one UNION ALL for the whole line + +If a line has more than one reference column (catalogVersion(...), unit(code), supercategories(code)), ImpEx resolves them all with one query. Here is what the JDBC log shows for such a line: + +```impex +INSERT_UPDATE Employee;uid[unique=true];sessionLanguage(isocode);sessionCurrency(isocode);defaultShipmentAddress(streetname,town) +;ih-emp6;fr;USD;ih-street-q3:Paris +``` + +```sql +SELECT x.a, x.b FROM ( + SELECT item_t0.PK AS a, 0 AS b FROM languages item_t0 + WHERE ( item_t0.p_isocode =?) AND (item_t0.TypePkString=? ) + UNION ALL + SELECT item_t1.PK AS a, 1 AS b FROM currencies item_t1 + WHERE ( item_t1.p_isocode =?) AND (item_t1.TypePkString=? ) + UNION ALL + SELECT item_t2.PK AS a, 2 AS b FROM addresses item_t2 + WHERE ( item_t2.p_streetname =? AND item_t2.p_town =?) AND (item_t2.TypePkString=? ) +) x +``` + +Column b is the translator number. It is used to distribute the results back to the columns. The parameters of each subquery are renamed (?v0 → ?t0v0, ?t1v0, …) so they don't collide. + +```groovy +// illustration +sb.append("SELECT x.a, x.b FROM ("); +for (int i = 0; i < translators.size(); i++) { + if (i > 0) sb.append(" UNION ALL "); + sb.append("{{").append(t.select()).append(" AS a, ").append(i).append(" AS b ") + .append(t.body().replaceAll("\\?v", "?t" + i + "v")).append("}}"); +} +sb.append(") x"); +``` + +Illustrative reconstruction, not platform source code. See the note above. + +The same mechanism works for collection elements in a single cell. Three groups in groups(uid) are also one query: + +```sql +SELECT x.a, x.b FROM ( + SELECT item_t0.PK AS a, 0 AS b FROM usergroups item_t0 WHERE ( item_t0.p_uid =?) AND (...) + UNION ALL + SELECT item_t1.PK AS a, 1 AS b FROM usergroups item_t1 WHERE ( item_t1.p_uid =?) AND (...) + UNION ALL + SELECT item_t2.PK AS a, 2 AS b FROM usergroups item_t2 WHERE ( item_t2.p_uid =?) AND (...) +) x +``` + +### The query goes through the FlexibleSearch cache +This is a regular FlexibleSearch query with a regular cache key. When I repeated the import with the same combination of language, currency, and address but a different uid, the query was not in the JDBC log: the result came from the cache. If thousands of lines reference the same catalog version and the same unit, this saves queries. If the combination of values is unique in every line, the cache fills up with single-use entries. And this is one more reason why the NOW() problem from the FlexibleSearch article applies to ImpEx too. + +### Chunks +The combined query is split into chunks, but not on every database. The default chunk size depends on the database: +```groovy +// illustration +int defaultChunkSize() { + boolean bigQueriesAreAProblem = isHana() || isOracle() || isSqlServer() || isMySQL8(); + return config.getInt("impex.query.chunk.size", bigQueriesAreAProblem ? 400 : 0); +} +``` + +Illustrative reconstruction, not platform source code. See the note above. + +0 means "don't split." On HANA, Oracle, SQL Server, and MySQL 8, the query is split into chunks of 400 subqueries; on the rest, which in practice means local HSQLDB, it is built in one piece. So locally on HSQLDB you are testing a different query from the one that will run in production in SAP Commerce Cloud on SQL Server. The query-chunk-size column modifier overrides this value, but only for collection elements in that column. The combined query across the columns of a line always uses the global value. If an import fails with "too many tables in query" on a line with a large collection, the modifier helps. If it fails on a line with many reference columns, only impex.query.chunk.size helps. + +### Turning it off +impex.query.combined=false (default true) brings back one query per cell. Sometimes this is the only way to get an import working on a database that chokes on long UNIONs. + +### Multi-pass import and the stop condition +Lines whose references didn't resolve are not treated as errors right away. They are written to a dump, and the dump is imported again. The classic case is a forward reference: + +```impex +INSERT_UPDATE Category;code[unique=true];catalogVersion(catalog(id),version)[unique=true] +;ih-cat-root;ih-catalog:Staged +INSERT_UPDATE CatalogVersion;catalog(id)[unique=true];version[unique=true] +;ih-catalog;Staged +INSERT_UPDATE Catalog;id[unique=true] +;ih-catalog +``` + +The category references a catalog version, which references a catalog, which is declared last. In the log: + +``` +Finished 1 pass ... - processed: 3, dumped: 2 (last pass: 0) +Starting pass 2 +Finished 2 pass ... - processed: 2, dumped: 1 (last pass: 2) +Starting pass 3 +Finished 3 pass ... - processed: 1, no lines dumped (last pass 1) +``` + +The import took three passes, one per link in the chain. + +Now a reference that will never resolve: + +```impex +INSERT_UPDATE Employee;uid[unique=true];sessionLanguage(isocode) +;ih-emp9;no_such_lang +``` + +``` +Finished 1 pass ... - processed: 1, dumped: 1 (last pass: 0) +Starting pass 2 +Finished 2 pass ... - processed: 1, dumped: 1 (last pass: 1) +Can not resolve any more lines ... Aborting further passes (at pass 2). +Finally could not import 1 lines! +``` + + +The condition for continuing looks like this: +```groovy +// illustration +boolean anotherPass = + (maxPass < 0 || currentPass <= maxPass) // maxPass defaults to -1: no limit + && (currentPass == 1 || dumpedNow < dumpedLastPass); // strictly fewer than last time +``` + + +Illustrative reconstruction, not platform source code. See the note above. + +The second pass always runs if anything is left after the first. The third and later passes run only if the number of deferred lines has strictly decreased. What follows from this in practice: + +A circular dependency in which neither item can be created without the other will never resolve. The import will stop at the second pass. +The Aborting further passes message means the number of deferred lines stopped decreasing. There is no limit on attempts by default at all. +A long dependency chain in a file costs a pass per link, and each pass rereads the whole dump. So the order of blocks affects import speed too. + + +### A line that wasn't imported can leave an item in the database +Let's look at what is in the dump for an unresolvable line (HAC shows it in the result block): + +```impex +INSERT_UPDATE Employee;uid[unique=true];sessionLanguage(isocode) +Employee,8809954312196,,,column 2: cannot resolve value 'no_such_lang' for attribute 'sessionLanguage';ih-emp9;no_such_lang +``` + + +The first cell contains the type and the PK. The key column is marked . This means the employee ih-emp9 was already created in the first pass with all the attributes that could be resolved. Only the unresolved part is deferred, to be written later by PK. And if the import ultimately "failed," the item stays in the database, without a language, but it exists: + +``` +userService.getUserForUID("ih-emp9") → EmployeeModel (8809954312196@1) +``` + +The import is not rolled back: after "Finally could not import 1 lines!" an incomplete item may remain in the database. + +### Validation errors also go to the second pass +If a save failed with a ModelSavingException (a validator, an interceptor, a uniqueness violation), the line is not considered finally failed. It goes to the dump with the message Failed to process item creation due to ModelSavingException. Retrying in the next turn. and runs again on the next pass. That's why validation error messages in ImpEx often look like this, with two line numbers: + +``` +Exception : line 4: cannot create Title ... found 1 item(s) using the same keys, +Exception : line 3: cannot create Title ... found 1 item(s) using the same keys +``` + +It is the same line: the number from the main file and the number from the second-pass dump. Interceptors with side effects will run twice on such a line. + +There is an undocumented key impex.retry.on.interceptorexceptions.only (default false, not present in any shipped .properties file) that narrows the retry to cases where the cause was specifically an InterceptorException. + +## Modifiers +The documentation describes about fifteen modifiers. The platform has 29 in a single list of constants, the header reads three more separately, and there is testMode, which is read directly in the code and declared nowhere. + +| Modifier | Where What it does | +|----|----| +| unique | column | part of the key used to find an existing item | +| allownull | column | allow null for a mandatory attribute| +| ignorenull | column | skip null collection elements| +| default | column | value for an empty cell| +| virtual | column | the column is absent from the data, only default| +| lang | column | language of a localized attribute| +| translator | column | custom value translator| +| cellDecorator | column | custom cell decorator| +| dateformat, numberformat | column | parsing formats| +| collection-delimiter | column | , by default| +| path-delimiter | column | : by default| +| key2value-delimiter | column | -> by default| +| map-delimiter | column | ; by default| +| mode | column | append / remove / merge for collections| +| query-chunk-size | column | chunk of the combined query, only for collection elements| +| forceWrite | column | write to a non-writable attribute| +| pos | column | explicit column position| +| alias | column | column name on export| +| sourceSystemId, pkFromExternalImportKey | column | external import keys| +| batchmode | header | UPDATE/REMOVE by a non-unique key, many items| +| cacheUnique | header | key → PK cache for the whole type| +| processor | header | custom ImportProcessor| +| parallel | header | false runs this block in one thread| +| ignoreKeyCase | header | case-insensitive key lookup| +| unlessExisting | header | skip existing items in INSERT| +| impex.legacy.mode | header | Jalo instead of ServiceLayer for this block| +| sld.enabled | header | read only by distributed ImpEx| +| disable.interceptor.types | header | disable interceptors by type (validate, prepare, …)| +| disable.interceptor.beans | header | disable interceptors by bean name| +| disable.UniqueAttributesValidator.for.types | header | disable the uniqueness check| +| testMode | header | with cacheUnique: check the cache against the database on every line| + +The last one, testMode, is a debug mode for cacheUnique. It rechecks every cache answer with a regular query and fails on a mismatch. It is not in the list of constants. + +Below are the ones that behave in non-obvious ways. + +### Without forceWrite the write is skipped with no error + +Every item has the sealed attribute, and it is not writable. Let's try writing it with and without the modifier: + +```impex +INSERT_UPDATE TestItemType2;foo[unique=true];bar +;ih-s1;x +;ih-s2;x +UPDATE TestItemType2;foo[unique=true];sealed +;ih-s1;true +UPDATE TestItemType2;foo[unique=true];sealed[forceWrite=true] +;ih-s2;true +``` + +``` +[ih-s1, null, ...] +[ih-s2, true, ...] +``` + + +HAC says "Import finished successfully." The ih-s1 line didn't change, and the only trace of this is a WARN in the console log: +``` +column sealed of type TestItemType2 is not writable, but you want to update it. +If you want to write this non writable attribute explicit, you have to use the +forceWrite=true modifier. This warning is printed only once for header. +Please check subsequent lines for similar problem. +``` + +"Printed only once for header" explains why in a large import you see one warning and think the problem is a one-off. + +An attribute that can only be set on creation (initial) can't be updated even with forceWrite: + +```impex +UPDATE TestItemType2;foo[unique=true];creationtime[dateformat=yyyy-MM-dd,forceWrite=true] +;ih-a4;2001-01-01 +``` + +``` +attribute de.hybris.platform.jalo.test.TestItem.creationtime cannot be changed except during item creation +``` + + +### unlessExisting works only in INSERT and only with the value true + +```impex +INSERT TestItemType2[unlessExisting=true];foo[unique=true];bar +;ih-a1;overwritten? +;ih-u1;new +INSERT TestItemType2[unlessExisting=yes];foo[unique=true];bar +;ih-a2;overwritten? +INSERT_UPDATE TestItemType2[unlessExisting=true];foo[unique=true];bar +;ih-a4;overwritten-by-insert-update +``` + + +Result: + +ih-a1 is untouched, ih-u1 is created, so the modifier works. +unlessExisting=yes is false: Cannot insert. Item exists: [8796093153305]. The value is parsed with Boolean.valueOf, so anything other than true in any case counts as false, and nothing is written to the log. +In INSERT_UPDATE the modifier is ignored with no warning: ih-a4 is overwritten. + +### ignoreKeyCase works only on the header + +The modifier looks like a column modifier, since it is about comparing the key value. But the lookup of an existing item reads it from the header: + + +```impex +INSERT_UPDATE TestItemType2;foo[unique=true,ignoreKeyCase=true];bar +;IH-A2;matched-case-insensitively? +INSERT_UPDATE TestItemType2[ignoreKeyCase=true];foo[unique=true];bar +;IH-A4;header-level +``` + +``` +ih-a2 -> abc"def ← not found +IH-A2 -> matched-case-insensitively? ← new item created +ih-a4 -> header-level ← found and updated +``` + +On a column the modifier is ignored, with no warning. + +Since we're talking about case: attribute names in the header are case-insensitive. INSERT_UPDATE TestItemType2;foo[unique=true];BAR writes to bar. + +### cacheUnique loads the keys of the whole type + +When the header starts, the engine fetches the keys of all items of the type: + +```impex +INSERT_UPDATE Employee[cacheUnique=true];uid[unique=true];name +;ih-emp6;Cached +``` + +``` +SELECT item_t0.PK, item_t0.p_uid FROM users item_t0 WHERE (item_t0.TypePkString=? ) +``` + + +No WHERE on the values. For a large update that touches most of the table, this pays off: one query instead of thousands. For a ten-line file against a ten-million-row table, it means reading ten million rows for the sake of ten. + +In an INSERT without a unique column, the modifier is not allowed: + +``` +You can not use cacheUnique modifier in INSERT mode when no column is unique, +use UPDATE / INSERT_UPDATE mode or declare at least one column as unique +``` + +And if the database already has two items with the same key value, the whole header fails: found more than one item for unique key values .... So cacheUnique also finds key duplicates that already exist in the database. + +### Collection prefixes (+), (-), and the undocumented (+?) + +The 2016 article had (+) and (-). There is a third prefix: + +| Prefix | Action | +|----|-----| +| (+) | add the element, always +| (-) | remove the element +| (+?) | add it if it isn't there yet + + +The difference between (+) and (+?) shows on a list attribute. fallbackLanguages on Language is a list: + +```impex +UPDATE Language;isocode[unique=true];fallbackLanguages(isocode) +;xx_test;en +;xx_test;(+) de +;xx_test;(+) de +;xx_test;(+?) en +;xx_test;(+?) fr +``` + +``` +[en, de, de, fr] +``` + + +(+) added `de` twice. (+?) didn't add the existing `en`. Sets (Set, for example groups on a user) won't have duplicates, so the difference only shows on lists. + +Prefixes can't be mixed with "bare" values in the same cell: + +``` +;ih-emp7;ih-g2,(+) ih-g3 +``` + +``` +Invalid syntax! The assigned collectionvalues must either have one of the prefixes +'(+)' or '(-)' or modifier mode must be set +``` + + +The mode=append|remove|merge modifier on a column sets the action for all values in the column at once. Without it, every value in the cell needs a prefix, not just the first one. + +### A header that turns off business logic + +Three header modifiers are not in the common list, but are read separately and put into the parameters of the session in which the save runs: + +``` +disable.interceptor.types=validate,prepare +disable.interceptor.beans='beanName1,beanName2' +disable.UniqueAttributesValidator.for.types='Title,Product' +``` + + +These modifiers turn off validation and business logic for one block of the file. An example is the interceptor that disables login for users. + +### ImpEx disables login for users + +The impex extension registers the disableLoginForImportedUserInterceptor interceptor. It fires on any User that ImpEx creates or modifies and sets loginDisabled=true if the user has no password. + +```impex +INSERT_UPDATE Employee;uid[unique=true];name +;ih-emp10;plain +INSERT_UPDATE Employee[disable.interceptor.beans='disableLoginForImportedUserInterceptor'];uid[unique=true];name +;ih-emp11;interceptor off +UPDATE Employee;uid[unique=true];name +;ih-emp-sl;just renamed +``` + + +The user ih-emp-sl had been created beforehand through ServiceLayer, with no password and loginDisabled=false. Result: + +``` +ih-emp10 loginDisabled=true name=plain +ih-emp11 loginDisabled=false name=interceptor off +ih-emp-sl loginDisabled=true name=just renamed +``` + + +### A plain UPDATE of the name through ImpEx blocked the user's login. If you have users without a local password (SSO, technical accounts), any ImpEx that touches them will disable their login without any error. + +The log shows: + +``` +Disabling login for 'null' because of empty password. +``` + +null, because the message prints the PK, and on creation there isn't one yet. + +How does the interceptor know ImpEx is running? From the session attributes that ImpEx sets for the duration of the save: impex.creation and impex.modification together with impex.modification.pk. Your own interceptor can check these attributes too, to behave differently during import. + +The interceptor is marked @Deprecated(since = "2211", forRemoval = true) but is enabled by default. It is turned off globally by the property disable.login.for.imported.user.interceptor.enabled=false, which appears in the shipped project.properties only in commented-out form. + +disable.UniqueAttributesValidator.for.types +The modifier does turn off the validator, which you can see from how the error changes: + +```impex +INSERT Title;code +;ih-title +INSERT Title[disable.UniqueAttributesValidator.for.types='Title'];code +;ih-title +``` + +``` +... due to [UniqueAttributesInterceptor]:ambiguous unique keys {code=ih-title} ... found 1 item(s) using the same keys +... due to Duplicate code 'ih-title' for type Title +``` + + +The first line was stopped by the uniqueness validator, the second by a check further down the stack. Title has one. When you disable the validator, you are relying on your type having one too. Check this on the specific type before leaving the modifier in the file. + +A practical rule: run grep -rn "disable\.\(interceptor\|UniqueAttributesValidator\)" --include=*.impex . across the whole project. These modifiers usually show up "temporarily." + +### Rewriting headers with impex.header.replacement +The documentation doesn't describe this mechanism, although the shorthands E1p, E1t, E1d, and C@ are used in every project with prices and classification. They are not ImpEx syntax but rules from advanced.properties: + +```impex +impex.header.replacement.1=C@(\\w+) ... @$1[system='\\$systemName',version='\\$systemVersion',translator='...ClassificationAttributeTranslator'] +impex.header.replacement.2=E1p ... europe1Prices[translator='de.hybris.platform.europe1.jalo.impex.Europe1PricesTranslator'] +impex.header.replacement.3=E1t ... europe1Taxes[translator='...Europe1TaxesTranslator'] +impex.header.replacement.4=E1d ... europe1Discounts[translator='...Europe1DiscountsTranslator'] +``` + + +Format: impex.header.replacement. = ... , with three dots as the separator. The rules are applied like this: + +```groovy +// illustration +for (int i = 1; i < columns.size(); i++) { // column 0 (mode and type) is not touched + for (Rule r : rulesByPriorityDesc) { + String replaced = columns.get(i).replaceAll(r.pattern, r.replacement); + if (!replaced.equals(columns.get(i))) { + columns.set(i, expandMacros(replaced)); // macros are expanded after the replacement + break; // the first rule that matches is the last one + } + } +} +``` + + +Illustrative reconstruction, not platform source code. See the note above. + +The properties are read every time a reader is created, so a rule can be added without a restart. I added one from the Groovy console: + +```impex +de.hybris.platform.util.Config.setParameter( + "impex.header.replacement.10", "barD ... bar[default='from-rule']") + +``` + +```impex +INSERT_UPDATE TestItemType2;foo[unique=true];barD +;ih-h3; +;ih-h4;explicit +``` + +``` +[ih-h3] bar=[from-rule] +[ih-h4] bar=[explicit] +``` + + +This is why the rule for C@ has \\$systemName: the replacement inserts a macro reference into the column, and the macro is expanded in the next step. + +The regex is not anchored: replaceAll looks for a match anywhere in the column name: + +```impex +INSERT_UPDATE TestItemType2;foo[unique=true];oldbarD +``` + +``` +INSERT_UPDATE TestItemType2;foo[unique=true];oldbar[default='from-rule'] +# unknown attribute 'oldbar' in header 'INSERT_UPDATE TestItemType2' +``` + + +The oldbarD column turned into oldbar[...]. With the standard rules, this means an attribute whose name contains E1p, E1t, or E1d will be mangled before the header is even parsed. Write your own rules with anchors: ^MyAttr$ ... myRealAttribute[...]. + +Programmatically, reader.addHeaderReplacementRule(src, tgt, prio) does the same. + +### Code inside ImpEx + +Lines starting with #% are code. By default (impex.legacy.scripting=true) it is executed by BeanShell. Half of the 2016 article was devoted to this. Almost all of it works, but there are a few differences I didn't write about back then. + +Without Enable code execution an if: block is always true +In the HAC import form, the Enable code execution checkbox is unchecked by default. In that case code is skipped with a WARN in the log. With an if: block it gets more interesting: + + +```impex +INSERT_UPDATE TestItemType2;foo[unique=true];bar +"#% if: ""a"".equals(""b"")" +;ih-nocode-inside-false-if;imported anyway? +#% endif: +``` + + +Without Enable code execution: + +``` +[ih-nocode-inside-false-if] bar=[imported anyway?] +``` + + +HAC: "Import finished successfully." The line was imported even though the condition is false: when code execution is off, the condition is not evaluated, and the engine treats it as true: + + +```groovy +// illustration +if (!(ifLine.getResult() instanceof Boolean)) { + result = codeExecutionEnabled + ? Boolean.FALSE // invalid expression: "false", with a WARN + : Boolean.TRUE; // code disabled: everything inside if: is imported +} +``` + +Illustrative reconstruction, not platform source code. See the note above. + +If you use if: for "this block is dev only" or "only if the extension is installed," a file imported without the checkbox imports everything. + +### A semicolon inside code disappears + +A code line is also a CSV line. A ; in it is a cell separator. In the default BeanShell mode, the engine assembles the code by concatenating all cells with no separator: + +```impex +#% impex.info("IH1 a;b;c"); +"#% impex.info(""IH2 a;b;c"");" +``` + +``` +IH1 abc +IH2 a;b;c +``` + +If there are two statements, you get a syntax error whose cause is hard to figure out: + +```impex +#% counter = counter + 1; impex.info("counter=" + counter); +``` + +``` +inline evaluation of: ``counter = counter + 1impex.info("IH3 counter=" + counter);'' +Encountered "impex" at line 1, column 22. +``` + +Hence the rule I followed in 2016 without explaining it: code in ImpEx is always written in quotes, and quotes inside are doubled. + +### One interpreter per file + +One BeanShell interpreter is created per reader and lives until the end of the file. Variables survive headers: + +```impex +#% counter = 1; +INSERT_UPDATE TestItemType2;foo[unique=true];bar +;ih-bsh1;x +INSERT_UPDATE TestItemType2;foo[unique=true];bar +"#% impex.info(""counter still visible="" + counter);" +``` + +``` +counter still visible=1 +``` + +The context always contains: + +| Variable | What it is | +|-----|------| +| impex | the reader itself (ImpExImportJob$MyImpExImportReader when importing from HAC) | +| jaloSession | the current Jalo session | +| line | Map of the current data line | +| currentLineNumber, currentLocation | position in the file | + +Plus the pre-imported packages de.hybris.platform.core, ...core.model.user, ...util, ...impex.jalo, ...jalo, ...jalo.c2l, ...jalo.user, ...jalo.flexiblesearch. That's why you can write Config.getBoolean(...) in code without an import. + +### beforeEach: can rewrite or drop a line + +The mechanism from the 2016 example with languages still works: + +```impex +INSERT_UPDATE TestItemType2;foo[unique=true];bar +"#% beforeEach: if (line.get(Integer.valueOf(2)).startsWith(""skip"")) line.clear(); else line.put(Integer.valueOf(2), line.get(Integer.valueOf(2)).toUpperCase());" +;ih-be1;make me loud +;ih-be2;skip me +#% beforeEach:end +;ih-be3;untouched +``` + +``` +[ih-be1] bar=[MAKE ME LOUD] +[ih-be3] bar=[untouched] +``` + +line.clear() is an undocumented way to filter out a line by a condition: an empty line is simply not imported. afterEach: works the same way, but after the item is saved, and it is called on every line (forEach: is its deprecated name and logs a WARN when used). + +### getLastImportedItem() returns a Jalo item + +Even in ServiceLayer Direct mode: + +```impex +"#% impex.info(""IH-LAST "" + impex.getLastImportedItem().getClass().getName());" +``` + +``` +IH-LAST de.hybris.platform.jalo.test.TestItem +``` + + +This is exactly why impex.getLastImportedItem().calculate() worked in the 2016 order example: it is a Jalo method of a Jalo object. To work with the model, you need modelService.get(impex.getLastImportedItem()). + +### Two 2016 recipes that no longer work +addDefinition from code. In 2016 you could define a macro from BeanShell. Now the method is protected, and BeanShell can't see it: + +```impex +#% impex.addDefinition("$dyn=from-code"); +``` + +``` +Error in method invocation: Method addDefinition ... +``` + + +Meanwhile, the unknown macro $dyn further down the file doesn't cause an error but stays in the data literally: bar=[$dyn]. A working workaround is to insert a definition line into the stream: + + +```impex +"#% m = new HashMap(); m.put(Integer.valueOf(0), ""$dyn=from-code-"" + (6 * 7)); impex.insertLine(m);" +INSERT_UPDATE TestItemType2;foo[unique=true];bar +;ih-def3;$dyn +``` + +``` +[ih-def3] bar=[from-code-42] +``` + + +includeSQLData with three arguments. The includeSQLData(url, driver, sql) signature from the 2016 article doesn't exist. There is (url, user, password, driverClass, sql), described below. + +$config- still works, though, if commerceservices is installed: + +```impex +UPDATE GenericItem[processor=de.hybris.platform.commerceservices.impex.impl.ConfigPropertyImportProcessor];pk[unique=true] +$workers=$config-impex.import.workers +INSERT_UPDATE TestItemType2;foo[unique=true];bar +;ih-cfg1;$workers +;ih-cfg2;$config-impex.legacy.scripting +``` + +``` +[ih-cfg1] bar=[4] +[ih-cfg2] bar=[true] +``` + +### #%groovy% with impex.legacy.scripting=true + +There is also a "modern" syntax that names the engine: #%groovy% ..., #%javascript% .... But it works only with impex.legacy.scripting=false. With the default value, the whole line, groovy% included, goes to BeanShell: + +```impex +#%groovy% impex.info("IH-GROOVY engine=" + this.getClass().getName()) +``` + +``` +IH-GROOVY engine=bsh.XThis +... inline evaluation of: ``groovy% impex.info(...)'' : illegal use of undefined variable, class, or 'void' literal +``` + + +The log message appeared before the error. BeanShell read groovy% impex.info(...) as the expression "groovy modulo impex.info(...)," evaluated the right operand, which means it called the method, and failed on the left one. If such a line contains something with a side effect, the side effect will happen, and the import will report an error. + +With impex.legacy.scripting=false, the same line is executed by Groovy (engine=Script73). But this mode has its own differences: the code is taken only from the first cell, that is, it is cut off at the first unquoted ; rather than concatenated. Old files with BeanShell code that has semicolons inside will break in a new way after the switch. + +### A code line stops parallel processing +Import is multithreaded by default: the reader distributes data lines into a queue, and workers save them. If the file has a code line, it has to see the result of all lines above it. So before each standalone #% line and before each new header, the reader waits for the queue to empty: + +```groovy +// illustration +@Override +protected void execute(CodeLine line, Map csvLine, boolean perLineHook) { + if (!perLineHook) { + waitForEmptyValueLineQueue(); // barrier: all workers must finish their work + } + super.execute(line, csvLine, perLineHook); +} +``` + +Illustrative reconstruction, not platform source code. See the note above. + +A #% impex.info("progress") line after every hundred data lines turns a multithreaded import into a sequence of short parallel stretches. The interpreter itself is guarded by synchronized, so beforeEach: / afterEach: also run strictly one at a time. + +The parallel=false header modifier switches a specific block to one thread without touching the others. + +## Files, the classpath, and other databases + +### Reading server files with file:, zip:, and jar: +A @media column with MediaDataTranslator accepts a path with a prefix: + +```impex +INSERT_UPDATE Media;code[unique=true];catalogVersion(catalog(id),version)[unique=true];mime;@media[translator=de.hybris.platform.impex.jalo.media.MediaDataTranslator] +;ih-m-file;ih-catalog:Staged;text/plain;file:/path/on/server/srvfile.txt +;ih-m-zip;ih-catalog:Staged;text/plain;zip:/path/on/server/arch.zip&inner/note.txt +;ih-m-jar;ih-catalog:Staged;application/octet-stream;jar:de.hybris.platform.impex.jalo.ImpExManager&ImpExManager.class +``` + +``` +ih-m-file size=37 data=hello from the app server filesystem +ih-m-zip size=24 data=hello from inside a zip +ih-m-jar size=29123 data=����...de/hybris/platform/impex/jalo/GeneratedImpExMan... +``` + + +file: reads any file accessible to the application server process. +zip: reads an entry from an archive on the server. The separator between the archive and the entry is &. +jar:Class&resource loads the class whose name is given in the cell and reads the resource through its class loader. In the example above, the bytecode of ImpExManager itself ended up in the media. + +### http: is broken and https: is not supported + +The http: prefix doesn't download the file; it writes the URL to the media. Or rather, it is supposed to: + +``` +;ih-m-http;ih-catalog:Staged;image/png;http://example.com/x.png +;ih-m-https;ih-catalog:Staged;image/png;https://example.com/x.png +``` + +``` +Exception : Error while setting URL to media +Path 'https://example.com/x.png' couldn't be resolved! +``` + +There is no https: prefix. And http: breaks because the engine cuts off the prefix before writing the URL: + +```groovy +// illustration +if (path.toLowerCase().startsWith("http:")) { + media.setURL(path.substring("http:".length())); // → "//example.com/x.png" +} +``` + + +Illustrative reconstruction, not platform source code. See the note above. + +What remains is //example.com/x.png, and it is rejected by MediaExternalUrlSourcesValidator, which doesn't appear in the ImpEx messages. If you repeat the write from Groovy, you see the real cause: + +Access protocol is not allowed for media URL //example.com/y.png. +Only: [https, http, fromjar] are allowed. +The same happens in legacy (Jalo) mode. The workaround is to duplicate the prefix: + +```impex +;ih-m-http3;ih-catalog:Staged;image/png;http:http://example.com/z.png +;ih-m-https3;ih-catalog:Staged;image/png;http:https://example.com/z.png +``` + +``` +ih-m-http3 url=http://example.com/z.png +ih-m-https3 url=https://example.com/z.png +``` + +In the failed case, the Media item is created anyway, with no URL and no data. This is the same "created but not imported" effect as in the section on passes. + +### Lines from another database with includeSQLData + +The impex variable is the reader with all its public methods. One of them opens a JDBC connection and substitutes the query result as data lines of the current header: + +```impex +INSERT_UPDATE TestItemType2;foo[unique=true];bar +"#% impex.includeSQLData(""jdbc:hsqldb:mem:ihdemo"", ""SA"", """", ""org.hsqldb.jdbcDriver"", ""SELECT 'ih-sql-' || TABLE_NAME, TABLE_TYPE FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'INFORMATION_SCHEMA' ORDER BY TABLE_NAME LIMIT 3"");" +``` + +``` +[ih-sql-ADMINISTRABLE_ROLE_AUTHORIZATIONS] bar=[VIEW] +[ih-sql-APPLICABLE_ROLES] bar=[VIEW] +[ih-sql-ASSERTIONS] bar=[VIEW] +``` + +The first column of the result goes to the first header column after the empty cell, the second to the second. For ETL this is a perfectly workable tool. Alongside it there is the includeExternalData(...) family for files and streams, and initDatabase(...) for several queries against the same database. + +### Security + +#% is arbitrary code on the server, file: and zip: are file system reads, jar: loads any class by name, and includeSQLData connects to any database the server can reach. The right to run an ImpEx import with code execution enabled is equivalent to the right to execute code on the server. Without code execution, server files can still be read through file:, zip:, and jar:. + +In HAC this is an administrator operation anyway. But ImpEx is often given to content managers through Backoffice, to integrations through ImportService, and to data loading pipelines. That's where this access is worth reviewing. + +The thread count is a SpEL expression +The number of workers comes from a property, and its value is a SpEL expression: + +```properties +impex.import.workers=#cores * 2 # project.properties +impex.import.workers.hsqldb=1 # advanced.properties: override by database name +``` + +```groovy +// illustration +int defaultMaxThreads(Tenant t) { + String expr = config("impex.import.workers." + t.databaseName().toLowerCase()); + if (isBlank(expr)) expr = config("impex.import.workers"); + return numberOfThreadsFromExpression(expr, 2); // #cores variable, fallback value 2 +} +``` + + +Illustrative reconstruction, not platform source code. See the note above. + +I ran several expressions through the same function on a machine with 14 cores: + +| Expression | Result +|-----|-----| +| #cores * 2 | 28 +| #cores + 2 | 16 +|4 | 4 +| #core * 2 (typo)| 2, with a WARN | +| cores * 2 (no #) | 2, with a WARN | +| #cores / 0 | 2, with a WARN | +| T(java.lang.Runtime).getRuntime().availableProcessors() | 2, with a WARN| +| #cores * 2,5 | exception SpelParseException | + +The evaluation context is restricted: arithmetic on #cores is available, but class access is not, so T(...) doesn't work. A typo drops you back to two threads with no error, and all that's left is the WARN Exception has been thrown during evaluation of '...'. Null will be returned. A syntax error, on the other hand, is not caught and is thrown out. + +On HSQLDB this setting has no effect: impex.import.workers.hsqldb=1 overrides the general value, and getDefaultMaxThreads returns 1. If you measure import speed locally on HSQLDB, you are measuring a single-threaded import. + +### Distributed ImpEx runs on a different engine + +The HAC import form has a Distributed mode checkbox. It is a separate implementation on top of the task engine: the file is cut into batches (impex.distributed.batch.size=100), the batches are stored in the database as ImportBatch / ImportBatchContent, and they are processed by tasks that can run on any node of the cluster. + +I ran a file with two ordinary lines, a code line, and an unresolvable reference through it: + +```impex +INSERT_UPDATE TestItemType2;foo[unique=true];bar +;ih-dist1;d1 +;ih-dist2;d2 +#% impex.info("IH-DIST code line"); +INSERT_UPDATE Employee;uid[unique=true];sessionLanguage(isocode) +;ih-dist-emp;no_such_lang +``` + + +The log shows that the code line ran once, when the file was being cut: IH-DIST code line appeared in the HTTP thread before the first batch processing task started. So anything that depends on order (getLastImportedItem(), counters, afterEach:) works differently in distributed mode than in regular mode. + +Models are saved in bulk: Number of models saved in bulk: 1. + +Retries happen in "turns" on a timer. The unresolvable line was processed four times: at 20:33:33, 20:34:03, 20:34:34, and 20:35:04, about 30 seconds apart on my installation. The stop condition is impex.distributed.noProgressionLimit=3 turns without progress. An import that would have failed in a fraction of a second in regular mode took more than three minutes in distributed mode. + +After a failure, the batches remain in the database. Before the run, ImportBatch and ImportBatchContent each had zero rows; after, 12 and 3. They are deleted only on success (impex.distributed.importbatchcontent.removeonsuccess=true). If your ImportBatchContent table keeps growing, those are traces of failed distributed imports. + +Distributed mode has its own combined query for resolving references, with its own switch: impex.distributed.query.for.each.line=false. + +## Reference of properties documented only in comments +Most of the keys documented only in comments are in ext/impex/project.properties. Together with the keys from advanced.properties and those read only by code: + +| Property | Default | What it does | +|------|-----|-----| + | impex.legacy.mode | false | Jalo instead of ServiceLayer for all operations + | | impex.legacy.scripting | true | BeanShell with cell concatenation; false enables engines via #%groovy%, etc. + | impex.query.combined | true | one UNION ALL per line + | impex.query.chunk.size | 400 / 0 | 400 for HANA, Oracle, SQL Server, MySQL 8; 0 for the rest (in practice, HSQLDB) + | impex.import.workers | #cores * 2 | SpEL; .hsqldb=1 and the like override per database + | impex.header.replacement.N | E1p, E1t, E1d, C@ | header rewriting rules + | impex.log.unresolved.lines | true | log deferred lines + | impex.retry.on.interceptorexceptions.only | false | retry on the next pass only for InterceptorException + | impex.clearing.model.context.after.processing.each.item.enabled | true | clear the model context after each item + | disable.login.for.imported.user.interceptor.enabled | true (in code) | loginDisabled for imported users without a password + | documentidregistry.disallow.ignored.values | true | disallow values in & references + | csv.maxmultilines | 10000 | how many lines can be glued together on an unmatched quote + | impex.distributed.batch.size | 100 | batch size + | impex.distributed.noProgressionLimit | 3 | turns without progress before stopping + | impex.distributed.importbatchcontent.removeonsuccess | true | delete batches only on success + | impex.distributed.query.for.each.line | false | separate switch for the combined query + | impex.import.service.distributed.enabled | false | distributed mode for all of ImportService + + + For impex.clearing.model.context.after.processing.each.item.enabled, the shipped comment itself admits that the enabled value can cause "significant performance degradation." If an import slowed down noticeably after an upgrade, this is the first candidate to check. But disabling it is a deliberate trade-off: validators will no longer be guaranteed to see fresh data. + +## Checklist +Without the Enable code execution checkbox, if: blocks are imported in full. Check how your files are imported in each of the paths: HAC, Backoffice, ImportService, system setup. +CSV errors are visible only in the console log, not in HAC. With an unmatched quote, the line number in the message is correct, but the text comes from a different line, and the lines in between disappear. + does not clear a reference. You can clear it only with an empty cell. +"Could not import N lines" doesn't mean the items don't exist. The line is created in the first pass, and the deferred part may never be written. +Aborting further passes (at pass 2): the number of deferred lines stopped decreasing; look for cycles and typos in keys. There is no pass limit. +forceWrite, unlessExisting=yes, ignoreKeyCase on a column, (+) on a list, and an unknown $macro don't produce an error, but the result differs from what is written. +cacheUnique on a small file against a large table fetches the keys of the whole type. +An ImpEx UPDATE of a user without a password disables their login (disableLoginForImportedUserInterceptor). SSO and technical accounts are hit first. +Find disable.interceptor.* and disable.UniqueAttributesValidator.for.types by grepping all the .impex files in the project. +Code in ImpEx is written in quotes, otherwise ; disappears. #%groovy% with default settings runs BeanShell. +#% lines in the middle of data put barriers into a multithreaded import. +http: for media works only with a double prefix; https: is not supported. +Access to import with code equals the right to execute code on the server; without code, server files can still be read through file:, zip:, and jar:. +A growing ImportBatchContent holds traces of failed distributed imports. +Import speed on HSQLDB is single-threaded; comparing it with production is meaningless. + +## Changes since 2016 + +Two of the 2016 recipes don't work: addDefinition from code (the method became protected) and the three-argument includeSQLData (that signature doesn't exist). One statement was wrong from the start: the backslash works in data lines too. Everything else (deletion via batchmode, if:, beforeEach: with line, $config-, (+) and (-)) works as before. Still, under every recipe there turned out to be a detail I should have mentioned back then. + +What surprised me most is how many failures in ImpEx HAC doesn't report: "Import finished successfully," and the database doesn't contain what the file does. And the errors ImpEx does produce often point to the wrong place: to a different line, to the second pass instead of the first, to null instead of the user ID. + +As with FlexibleSearch, for a component designed in the early 2000s and compatible with every file ever imported, this is understandable. There is one practical rule to take from this: verify the ImpEx result against the database, for example with a FlexibleSearch query on the imported keys and a comparison of item counts. diff --git a/docs/dev/impex/impex.tmLanguage.json b/docs/dev/impex/impex.tmLanguage.json new file mode 100644 index 00000000..c23a0bb9 --- /dev/null +++ b/docs/dev/impex/impex.tmLanguage.json @@ -0,0 +1,87 @@ +{ + "$schema": "https://raw.githubusercontent.com/martinring/tmlanguage/master/tmlanguage.json", + "name": "ImpEx", + "fileTypes": [ + "impex" + ], + "patterns": [ + { + "include": "#keywords" + }, + { + "include": "#strings" + }, + { + "include": "#comment" + }, + { + "include": "#declaration" + }, + { + "include": "#punctuation" + }, + { + "include": "#constant" + } + ], + "repository": { + "keywords": { + "patterns": [ + { + "name": "keyword.control.header.impex", + "match": "(?i)^(INSERT_UPDATE|INSERT|UPDATE|REMOVE)\\s+" + }, + { + "name": "constant.language.impex", + "match": "(?i)\\b(true|false)\\b" + } + ] + }, + "strings": { + "patterns": [{ + "name": "string.quoted.double.impex", + "begin": "\"", + "end": "\"", + "patterns": [{ + "name": "constant.character.escape.impex", + "match": "\\\\." + }] + }] + }, + "comment": { + "patterns": [{ + "name": "comment.line.impex", + "match": "^#.+$" + }] + }, + "declaration": { + "patterns": [ + { + "name": "variable.name.impex", + "match": "\\$[a-zA-Z0-9]+" + } + ] + }, + "punctuation": { + "patterns": [ + { + "name": "punctuation.separator.impex", + "match": ";" + }, + { + "name": "punctuation.separator.impex", + "match": "," + } + ] + }, + "constant": { + "patterns": [ + { + "name": "constant.numeric", + "match": "\\b([0-9]+)\\b" + } + ] + } + }, + "scopeName": "text.tabular.impex" +} From 7128c7793f056db21c0e5d5de0dd10d3f1e5b37d Mon Sep 17 00:00:00 2001 From: Pawel Wolanski Date: Sat, 21 Nov 2026 01:49:04 +0100 Subject: [PATCH 02/25] feat(impex): add Generic Editor preview Keep the legacy editor available during migration. Package a TM4E grammar\nand verify quotes, comments, scopes, and extension class resolution.\nFormatting, completion, wizard, and LSP services follow in later slices. --- com.hybris.hyeclipse.feature/feature.xml | 7 + .../META-INF/MANIFEST.MF | 13 ++ .../build.properties | 3 + com.hybris.hyeclipse.impex.tests/pom.xml | 14 ++ .../impex/tests/ImpexGrammarTest.java | 106 +++++++++++++++ .../impex/tests/ImpexRegistrationTest.java | 69 ++++++++++ .../META-INF/MANIFEST.MF | 13 ++ com.hybris.hyeclipse.impex/README.md | 26 ++++ com.hybris.hyeclipse.impex/build.properties | 4 + com.hybris.hyeclipse.impex/plugin.properties | 3 + com.hybris.hyeclipse.impex/plugin.xml | 23 ++++ com.hybris.hyeclipse.impex/pom.xml | 14 ++ .../syntaxes/impex.tmLanguage.json | 128 ++++++++++++++++++ docs/dev/impex/editor-replacement-plan.md | 32 ++++- docs/dev/impex/impex.tmLanguage.json | 87 ------------ pom.xml | 2 + 16 files changed, 452 insertions(+), 92 deletions(-) create mode 100644 com.hybris.hyeclipse.impex.tests/META-INF/MANIFEST.MF create mode 100644 com.hybris.hyeclipse.impex.tests/build.properties create mode 100644 com.hybris.hyeclipse.impex.tests/pom.xml create mode 100644 com.hybris.hyeclipse.impex.tests/src/com/hybris/hyeclipse/impex/tests/ImpexGrammarTest.java create mode 100644 com.hybris.hyeclipse.impex.tests/src/com/hybris/hyeclipse/impex/tests/ImpexRegistrationTest.java create mode 100644 com.hybris.hyeclipse.impex/META-INF/MANIFEST.MF create mode 100644 com.hybris.hyeclipse.impex/README.md create mode 100644 com.hybris.hyeclipse.impex/build.properties create mode 100644 com.hybris.hyeclipse.impex/plugin.properties create mode 100644 com.hybris.hyeclipse.impex/plugin.xml create mode 100644 com.hybris.hyeclipse.impex/pom.xml create mode 100644 com.hybris.hyeclipse.impex/syntaxes/impex.tmLanguage.json delete mode 100644 docs/dev/impex/impex.tmLanguage.json diff --git a/com.hybris.hyeclipse.feature/feature.xml b/com.hybris.hyeclipse.feature/feature.xml index 6876e274..5081aabc 100755 --- a/com.hybris.hyeclipse.feature/feature.xml +++ b/com.hybris.hyeclipse.feature/feature.xml @@ -107,6 +107,13 @@ All rights reserved. version="0.0.0" unpack="false"/> + + + + 4.0.0 + + com.hybris.hyeclipse + com.hybris.hyeclipse.parent + 22.11.1-SNAPSHOT + + com.hybris.hyeclipse.impex.tests + eclipse-test-plugin + SAP Commerce Cloud - ImpEx language tests + diff --git a/com.hybris.hyeclipse.impex.tests/src/com/hybris/hyeclipse/impex/tests/ImpexGrammarTest.java b/com.hybris.hyeclipse.impex.tests/src/com/hybris/hyeclipse/impex/tests/ImpexGrammarTest.java new file mode 100644 index 00000000..dd5d78be --- /dev/null +++ b/com.hybris.hyeclipse.impex.tests/src/com/hybris/hyeclipse/impex/tests/ImpexGrammarTest.java @@ -0,0 +1,106 @@ +/******************************************************************************* + * Copyright 2020 SAP + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + ******************************************************************************/ +package com.hybris.hyeclipse.impex.tests; + +import java.io.InputStream; +import java.nio.charset.StandardCharsets; + +import org.eclipse.core.runtime.Platform; +import org.eclipse.tm4e.core.grammar.IGrammar; +import org.eclipse.tm4e.core.grammar.IToken; +import org.eclipse.tm4e.core.grammar.ITokenizeLineResult; +import org.eclipse.tm4e.core.registry.IGrammarSource; +import org.eclipse.tm4e.core.registry.Registry; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +public class ImpexGrammarTest { + + private IGrammar grammar; + + @Before + public void loadGrammar() throws Exception { + try (final InputStream stream = Platform.getBundle("com.hybris.hyeclipse.impex") + .getEntry("syntaxes/impex.tmLanguage.json").openStream()) { + grammar = new Registry().addGrammar(IGrammarSource.fromString(IGrammarSource.ContentType.JSON, + new String(stream.readAllBytes(), StandardCharsets.UTF_8))); + } + } + + @Test + public void highlightsHeadersAndModifiers() { + final String line = "INSERT_UPDATE Product;code[unique=true];catalogVersion(catalog(id),version)"; + assertScope(grammar.tokenizeLine(line), 0, "keyword.control.header.impex"); + assertScope(grammar.tokenizeLine(line), line.indexOf("Product"), "entity.name.type.impex"); + assertScope(grammar.tokenizeLine(line), line.indexOf("unique"), "entity.other.attribute-name.modifier.impex"); + } + + @Test + public void distinguishesScriptsAndComments() { + assertScope(grammar.tokenizeLine("#% beforeEach: line.clear();"), 0, "keyword.control.script.impex"); + assertScope(grammar.tokenizeLine("\"#% if: \"\"a\"\".equals(\"\"b\"\")\""), 1, + "keyword.control.script.impex"); + assertScope(grammar.tokenizeLine("\"# quoted comment\";data"), 1, "comment.line.number-sign.impex"); + assertScope(grammar.tokenizeLine("#"), 0, "comment.line.number-sign.impex"); + assertNoScope(grammar.tokenizeLine(";code;value # not a comment"), 12, "comment.line.number-sign.impex"); + } + + @Test + public void quoteInsideUnquotedCellDoesNotStartString() { + assertNoScope(grammar.tokenizeLine(";code;abc\"def"), 9, "string.quoted.double.impex"); + } + + @Test + public void doublesQuotesAndDoesNotEscapeWithBackslash() { + assertScope(grammar.tokenizeLine(";code;\"5\"\" monitor\""), 8, "constant.character.escape.impex"); + final String line = ";code;\"5\\\" monitor"; + assertNoScope(grammar.tokenizeLine(line), line.indexOf("monitor"), "string.quoted.double.impex"); + } + + @Test + public void preservesMultilineStringState() { + final ITokenizeLineResult first = grammar.tokenizeLine(";code;\"line1"); + final String secondLine = "line2\";plain"; + final ITokenizeLineResult second = grammar.tokenizeLine(secondLine, first.getRuleStack(), null); + assertScope(second, 0, "string.quoted.double.impex"); + assertNoScope(second, secondLine.indexOf("plain"), "string.quoted.double.impex"); + } + + @Test + public void recognizesHyphenatedMacrosAndCollectionPrefixes() { + assertScope(grammar.tokenizeLine("$config-value=example"), 0, "variable.other.definition.impex"); + final String line = ";$config-value;(+?) item;"; + assertScope(grammar.tokenizeLine(line), 1, "variable.other.impex"); + assertScope(grammar.tokenizeLine(line), line.indexOf("(+?)"), "keyword.operator.collection.impex"); + assertScope(grammar.tokenizeLine(line), line.indexOf(""), "constant.language.impex"); + } + + private void assertScope(final ITokenizeLineResult result, final int offset, final String scope) { + Assert.assertTrue("Expected " + scope + " at " + offset, hasScope(result, offset, scope)); + } + + private void assertNoScope(final ITokenizeLineResult result, final int offset, final String scope) { + Assert.assertFalse("Unexpected " + scope + " at " + offset, hasScope(result, offset, scope)); + } + + private boolean hasScope(final ITokenizeLineResult result, final int offset, final String scope) { + for (final IToken token : result.getTokens()) { + if (token.getStartIndex() <= offset && offset < token.getEndIndex()) { + return token.getScopes().contains(scope); + } + } + return false; + } +} diff --git a/com.hybris.hyeclipse.impex.tests/src/com/hybris/hyeclipse/impex/tests/ImpexRegistrationTest.java b/com.hybris.hyeclipse.impex.tests/src/com/hybris/hyeclipse/impex/tests/ImpexRegistrationTest.java new file mode 100644 index 00000000..7df0f804 --- /dev/null +++ b/com.hybris.hyeclipse.impex.tests/src/com/hybris/hyeclipse/impex/tests/ImpexRegistrationTest.java @@ -0,0 +1,69 @@ +/******************************************************************************* + * Copyright 2020 SAP + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + ******************************************************************************/ +package com.hybris.hyeclipse.impex.tests; + +import org.eclipse.core.runtime.IConfigurationElement; +import org.eclipse.core.runtime.Platform; +import org.eclipse.core.runtime.content.IContentType; +import org.junit.Assert; +import org.junit.Test; + +public class ImpexRegistrationTest { + + @Test + public void recognizesImpexWithoutClaimingCsvFiles() { + final IContentType type = Platform.getContentTypeManager() + .getContentType("com.hybris.hyeclipse.impex.impex"); + Assert.assertNotNull(type); + Assert.assertTrue(type.isAssociatedWith("example.impex")); + Assert.assertFalse(type.isAssociatedWith("example.csv")); + } + + @Test + public void previewEditorClassExistsAndIsNotDefault() throws Exception { + for (final IConfigurationElement element : Platform.getExtensionRegistry() + .getConfigurationElementsFor("org.eclipse.ui.editors")) { + if ("com.hybris.hyeclipse.impex.editor".equals(element.getAttribute("id"))) { + Assert.assertEquals("false", element.getAttribute("default")); + Assert.assertNotNull(Platform.getBundle("com.hybris.hyeclipse.impex") + .loadClass(element.getAttribute("class"))); + return; + } + } + Assert.fail("ImpEx preview editor is not registered"); + } + + @Test + public void grammarBindingAndPresentationClassExist() throws Exception { + boolean bound = false; + for (final IConfigurationElement element : Platform.getExtensionRegistry() + .getConfigurationElementsFor("org.eclipse.tm4e.registry.grammars")) { + if ("scopeNameContentTypeBinding".equals(element.getName()) + && "com.hybris.hyeclipse.impex.impex".equals(element.getAttribute("contentTypeId"))) { + Assert.assertEquals("text.tabular.impex", element.getAttribute("scopeName")); + bound = true; + } + } + Assert.assertTrue("ImpEx grammar is not bound to its content type", bound); + for (final IConfigurationElement element : Platform.getExtensionRegistry() + .getConfigurationElementsFor("org.eclipse.ui.genericeditor.presentationReconcilers")) { + if ("com.hybris.hyeclipse.impex.impex".equals(element.getAttribute("contentType"))) { + Assert.assertNotNull(Platform.getBundle("com.hybris.hyeclipse.impex") + .loadClass(element.getAttribute("class"))); + return; + } + } + Assert.fail("ImpEx presentation reconciler is not registered"); + } +} diff --git a/com.hybris.hyeclipse.impex/META-INF/MANIFEST.MF b/com.hybris.hyeclipse.impex/META-INF/MANIFEST.MF new file mode 100644 index 00000000..3c9a304c --- /dev/null +++ b/com.hybris.hyeclipse.impex/META-INF/MANIFEST.MF @@ -0,0 +1,13 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: %bundleName +Bundle-SymbolicName: com.hybris.hyeclipse.impex;singleton:=true +Bundle-Version: 22.11.1.qualifier +Bundle-Vendor: SAP +Bundle-RequiredExecutionEnvironment: JavaSE-21 +Bundle-Localization: plugin +Require-Bundle: org.eclipse.core.contenttype, + org.eclipse.ui.genericeditor, + org.eclipse.tm4e.registry, + org.eclipse.tm4e.ui +Automatic-Module-Name: com.hybris.hyeclipse.impex diff --git a/com.hybris.hyeclipse.impex/README.md b/com.hybris.hyeclipse.impex/README.md new file mode 100644 index 00000000..2616fd81 --- /dev/null +++ b/com.hybris.hyeclipse.impex/README.md @@ -0,0 +1,26 @@ +# ImpEx editor preview + +Generic Editor/TM4E foundation for the [migration plan](../docs/dev/impex/editor-replacement-plan.md). +The legacy `com.hybris.hyeclipse.impexed` bundle remains in the main feature. + +After installing the rebuilt feature, choose **Open With > ImpEx Editor (Preview)** +on an `.impex` file. The preview is not registered as the default editor and does +not claim `.csv` files. Colors follow the installed TM4E theme. + +The canonical grammar is `syntaxes/impex.tmLanguage.json`. Headers, modifiers, +macros, data-cell strings, comments, and script directives have initial scopes; +this is not a complete ImpEx parser. Backslash-continuation context and configurable +header replacements still require further work. + +Formatting, type-system completion/navigation, the new-file wizard, and LSP server +integration are not implemented yet. Use the legacy editor for those workflows. + +Run the isolated OSGi tests: + +```bash +./mvnw -pl com.hybris.hyeclipse.impex,com.hybris.hyeclipse.impex.tests -am verify +``` + +The tests exercise the packaged grammar in TM4E and check extension registration +and class resolution. They do not replace interactive light/dark-theme and +existing-workspace upgrade testing. diff --git a/com.hybris.hyeclipse.impex/build.properties b/com.hybris.hyeclipse.impex/build.properties new file mode 100644 index 00000000..7a84e960 --- /dev/null +++ b/com.hybris.hyeclipse.impex/build.properties @@ -0,0 +1,4 @@ +bin.includes = META-INF/,\ + plugin.xml,\ + plugin.properties,\ + syntaxes/ diff --git a/com.hybris.hyeclipse.impex/plugin.properties b/com.hybris.hyeclipse.impex/plugin.properties new file mode 100644 index 00000000..6f1bbe61 --- /dev/null +++ b/com.hybris.hyeclipse.impex/plugin.properties @@ -0,0 +1,3 @@ +bundleName=SAP Commerce Cloud - ImpEx language support +contentTypeName=ImpEx +editorName=ImpEx Editor (Preview) diff --git a/com.hybris.hyeclipse.impex/plugin.xml b/com.hybris.hyeclipse.impex/plugin.xml new file mode 100644 index 00000000..ba920761 --- /dev/null +++ b/com.hybris.hyeclipse.impex/plugin.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + diff --git a/com.hybris.hyeclipse.impex/pom.xml b/com.hybris.hyeclipse.impex/pom.xml new file mode 100644 index 00000000..55ba3270 --- /dev/null +++ b/com.hybris.hyeclipse.impex/pom.xml @@ -0,0 +1,14 @@ + + + 4.0.0 + + com.hybris.hyeclipse + com.hybris.hyeclipse.parent + 22.11.1-SNAPSHOT + + com.hybris.hyeclipse.impex + eclipse-plugin + SAP Commerce Cloud - ImpEx language support + diff --git a/com.hybris.hyeclipse.impex/syntaxes/impex.tmLanguage.json b/com.hybris.hyeclipse.impex/syntaxes/impex.tmLanguage.json new file mode 100644 index 00000000..f5fecf67 --- /dev/null +++ b/com.hybris.hyeclipse.impex/syntaxes/impex.tmLanguage.json @@ -0,0 +1,128 @@ +{ + "$schema": "https://raw.githubusercontent.com/martinring/tmlanguage/master/tmlanguage.json", + "name": "ImpEx", + "scopeName": "text.tabular.impex", + "fileTypes": ["impex"], + "patterns": [ + {"include": "#quoted-script"}, + {"include": "#script"}, + {"include": "#quoted-comment"}, + {"name": "comment.line.number-sign.impex", "match": "^\\s*#(?!%).*$"}, + {"include": "#macro-definition"}, + {"include": "#header"}, + {"include": "#data"}, + {"include": "#first-quoted-cell"}, + {"include": "#macro"} + ], + "repository": { + "quoted-script": { + "name": "meta.embedded.script.impex", + "begin": "^\\s*(\")(#%)", + "beginCaptures": { + "1": {"name": "punctuation.definition.string.begin.impex"}, + "2": {"name": "keyword.control.script.impex"} + }, + "end": "\"(?!\")", + "endCaptures": {"0": {"name": "punctuation.definition.string.end.impex"}}, + "patterns": [{"include": "#doubled-quote"}, {"include": "#script-directive"}] + }, + "script": { + "name": "meta.embedded.script.impex", + "begin": "^\\s*(#%)", + "beginCaptures": {"1": {"name": "keyword.control.script.impex"}}, + "end": "$", + "patterns": [{"include": "#script-directive"}] + }, + "script-directive": { + "patterns": [ + {"name": "keyword.control.script.impex", "match": "\\b(?:if|endif|beforeEach|afterEach|forEach):(?:end\\b)?"}, + {"name": "storage.type.script.impex", "match": "\\b(?:groovy|javascript|beanshell)%"} + ] + }, + "quoted-comment": { + "name": "comment.line.number-sign.impex", + "begin": "^\\s*\"\\s*#(?!%)", + "end": "\"(?!\")", + "patterns": [{"include": "#doubled-quote"}] + }, + "macro-definition": { + "begin": "^\\s*(\\$[\\w-]+)(\\s*=)", + "beginCaptures": { + "1": {"name": "variable.other.definition.impex"}, + "2": {"name": "keyword.operator.assignment.impex"} + }, + "end": "$", + "patterns": [{"include": "#macro"}] + }, + "header": { + "name": "meta.header.impex", + "begin": "(?i)^\\s*(INSERT_UPDATE|INSERT|UPDATE|REMOVE)\\s+([\\w.]+)", + "beginCaptures": { + "1": {"name": "keyword.control.header.impex"}, + "2": {"name": "entity.name.type.impex"} + }, + "end": "$", + "patterns": [ + {"include": "#modifiers"}, + {"include": "#macro"}, + {"name": "entity.other.attribute-name.impex", "match": "[@&]?[A-Za-z_][\\w.-]*"}, + {"name": "punctuation.separator.impex", "match": "[;,()]"} + ] + }, + "modifiers": { + "begin": "\\[", + "beginCaptures": {"0": {"name": "punctuation.section.brackets.begin.impex"}}, + "end": "\\]", + "endCaptures": {"0": {"name": "punctuation.section.brackets.end.impex"}}, + "patterns": [ + {"name": "string.quoted.single.impex", "begin": "'", "end": "'", "patterns": [{"include": "#macro"}]}, + {"name": "string.quoted.double.impex", "begin": "\"", "end": "\"(?!\")", "patterns": [{"include": "#doubled-quote"}, {"include": "#macro"}]}, + {"name": "entity.other.attribute-name.modifier.impex", "match": "[\\w.-]+(?=\\s*=)"}, + {"include": "#macro"}, + {"include": "#scalar"}, + {"name": "keyword.operator.assignment.impex", "match": "="}, + {"name": "punctuation.separator.impex", "match": ","} + ] + }, + "data": { + "begin": "^\\s*(?=;)", + "end": "$", + "patterns": [ + {"include": "#quoted-cell"}, + {"name": "punctuation.separator.impex", "match": ";"}, + {"include": "#unquoted-cell"} + ] + }, + "quoted-cell": { + "name": "string.quoted.double.impex", + "begin": "(?<=;)\\s*\"", + "end": "\"(?!\")", + "patterns": [{"include": "#doubled-quote"}, {"include": "#macro"}] + }, + "first-quoted-cell": { + "name": "string.quoted.double.impex", + "begin": "^\\s*\"", + "end": "\"(?!\")", + "patterns": [{"include": "#doubled-quote"}, {"include": "#macro"}] + }, + "unquoted-cell": { + "begin": "(?<=;)(?!\\s*\")(?=[^;\\r\\n])", + "end": "(?=;|$)", + "patterns": [ + {"include": "#macro"}, + {"include": "#scalar"}, + {"name": "constant.language.impex", "match": "(?i)<(?:ignore|null)>"}, + {"name": "keyword.operator.collection.impex", "match": "\\((?:\\+\\?|\\+|-)\\)"}, + {"name": "punctuation.separator.continuation.impex", "match": "\\\\$"} + ] + }, + "doubled-quote": {"name": "constant.character.escape.impex", "match": "\"\""}, + "macro": {"name": "variable.other.impex", "match": "\\$[\\w-]+"}, + "scalar": { + "patterns": [ + {"name": "constant.language.impex", "match": "(?i)(? ImpEx Editor (Preview)** as a non-default Generic + Editor, with an ImpEx content type and TM4E presentation reconciler. +- Moved the grammar into the production bundle as the canonical resource; + implemented initial header/modifier/macro/data/comment/script scopes and + cell-aware quoting. Grammar and extension-registration tests cover this slice. +- The 2026-09 target supplies TM4E. Its Generic Editor implementation class is + `org.eclipse.ui.internal.genericeditor.ExtensionBasedTextEditor`; the preview + registration uses it directly and tests class resolution. Recheck this internal + entry point on future platform upgrades. +- Verification: 9 new OSGi tests passed; the full 20-module package build passed + with tests skipped after the isolated test run. The resulting p2 ZIP contains + both editors and the packaged grammar. Interactive UI/upgrade checks remain. +- Next: continuation-aware lexical scanning, the new-file wizard, and LSP + lifecycle, formatting, and project-scoped type-system services. These features + are not implemented by the preview, and the legacy editor must not be retired. ## Goal and scope @@ -16,7 +36,8 @@ Inputs: - [ImpEx behavior notes](impex-docs.md): reference for lexical edge cases, not a complete formal language specification. Runtime-dependent claims require verification against the supported Commerce version. -- [TextMate grammar](impex.tmLanguage.json): starting point, not production-ready. +- [TextMate grammar](../../../com.hybris.hyeclipse.impex/syntaxes/impex.tmLanguage.json): + canonical packaged grammar, still under migration. - Existing `com.hybris.hyeclipse.impexed/plugin.xml`, editor, wizard, formatter, completion processors, and hyperlink classes. @@ -56,9 +77,10 @@ p2 feature resolves these dependencies, not just the development target. ## Grammar corrections -The current grammar starts a string on any quote, treats `\\.` as an escape, -recognizes only unquoted `#` comments, and cannot distinguish scripts from -comments. Correct these before editor cutover: +The original supplied grammar started a string on any quote, treated `\\.` as +an escape, recognized only unquoted `#` comments, and could not distinguish +scripts from comments. The preview fixes initial cases; complete and validate +the following behavior before editor cutover: - Model cell boundaries and quoted multiline cells; quoting starts at the beginning of a cell, allowing leading whitespace as verified by fixtures. diff --git a/docs/dev/impex/impex.tmLanguage.json b/docs/dev/impex/impex.tmLanguage.json deleted file mode 100644 index c23a0bb9..00000000 --- a/docs/dev/impex/impex.tmLanguage.json +++ /dev/null @@ -1,87 +0,0 @@ -{ - "$schema": "https://raw.githubusercontent.com/martinring/tmlanguage/master/tmlanguage.json", - "name": "ImpEx", - "fileTypes": [ - "impex" - ], - "patterns": [ - { - "include": "#keywords" - }, - { - "include": "#strings" - }, - { - "include": "#comment" - }, - { - "include": "#declaration" - }, - { - "include": "#punctuation" - }, - { - "include": "#constant" - } - ], - "repository": { - "keywords": { - "patterns": [ - { - "name": "keyword.control.header.impex", - "match": "(?i)^(INSERT_UPDATE|INSERT|UPDATE|REMOVE)\\s+" - }, - { - "name": "constant.language.impex", - "match": "(?i)\\b(true|false)\\b" - } - ] - }, - "strings": { - "patterns": [{ - "name": "string.quoted.double.impex", - "begin": "\"", - "end": "\"", - "patterns": [{ - "name": "constant.character.escape.impex", - "match": "\\\\." - }] - }] - }, - "comment": { - "patterns": [{ - "name": "comment.line.impex", - "match": "^#.+$" - }] - }, - "declaration": { - "patterns": [ - { - "name": "variable.name.impex", - "match": "\\$[a-zA-Z0-9]+" - } - ] - }, - "punctuation": { - "patterns": [ - { - "name": "punctuation.separator.impex", - "match": ";" - }, - { - "name": "punctuation.separator.impex", - "match": "," - } - ] - }, - "constant": { - "patterns": [ - { - "name": "constant.numeric", - "match": "\\b([0-9]+)\\b" - } - ] - } - }, - "scopeName": "text.tabular.impex" -} diff --git a/pom.xml b/pom.xml index 3a0aeebc..53378b40 100644 --- a/pom.xml +++ b/pom.xml @@ -50,6 +50,8 @@ com.hybris.hyeclipse.commons com.hybris.hyeclipse.hac com.hybris.hyeclipse.impexed + com.hybris.hyeclipse.impex + com.hybris.hyeclipse.impex.tests com.hybris.hyeclipse.importer com.hybris.hyeclipse.ytypesystem com.hybris.hyeclipse.platform From 29d76aad602646557e235f338c8c9ba90895561d Mon Sep 17 00:00:00 2001 From: Pawel Wolanski Date: Sat, 21 Nov 2026 02:24:31 +0100 Subject: [PATCH 03/25] feat(impex): migrate new-file wizard Move the existing wizard and shortcut IDs to the preview bundle. Refuse overwrites and use a project rule for file charset metadata. Keep the legacy editor for formatting and type completion. --- .../META-INF/MANIFEST.MF | 5 +- .../impex/tests/ImpexFileCreatorTest.java | 185 ++++++++++++++++++ .../impex/tests/ImpexRegistrationTest.java | 37 ++++ .../META-INF/MANIFEST.MF | 7 + com.hybris.hyeclipse.impex/README.md | 21 +- com.hybris.hyeclipse.impex/build.properties | 2 + com.hybris.hyeclipse.impex/plugin.properties | 4 + com.hybris.hyeclipse.impex/plugin.xml | 17 ++ .../impex/wizards/ImpexFileCreator.java | 117 +++++++++++ .../hyeclipse/impex/wizards/Messages.java | 37 ++++ .../impex/wizards/Messages.properties | 8 + .../impex/wizards/NewImpexWizard.java | 141 +++++++++++++ .../impex/wizards/NewImpexWizardHandler.java | 40 ++++ com.hybris.hyeclipse.impexed/plugin.xml | 29 +-- docs/dev/impex/editor-replacement-plan.md | 11 +- 15 files changed, 625 insertions(+), 36 deletions(-) create mode 100644 com.hybris.hyeclipse.impex.tests/src/com/hybris/hyeclipse/impex/tests/ImpexFileCreatorTest.java create mode 100644 com.hybris.hyeclipse.impex/src/com/hybris/hyeclipse/impex/wizards/ImpexFileCreator.java create mode 100644 com.hybris.hyeclipse.impex/src/com/hybris/hyeclipse/impex/wizards/Messages.java create mode 100644 com.hybris.hyeclipse.impex/src/com/hybris/hyeclipse/impex/wizards/Messages.properties create mode 100644 com.hybris.hyeclipse.impex/src/com/hybris/hyeclipse/impex/wizards/NewImpexWizard.java create mode 100644 com.hybris.hyeclipse.impex/src/com/hybris/hyeclipse/impex/wizards/NewImpexWizardHandler.java diff --git a/com.hybris.hyeclipse.impex.tests/META-INF/MANIFEST.MF b/com.hybris.hyeclipse.impex.tests/META-INF/MANIFEST.MF index c04dacda..bf247505 100644 --- a/com.hybris.hyeclipse.impex.tests/META-INF/MANIFEST.MF +++ b/com.hybris.hyeclipse.impex.tests/META-INF/MANIFEST.MF @@ -8,6 +8,9 @@ Bundle-RequiredExecutionEnvironment: JavaSE-21 Require-Bundle: org.junit, org.eclipse.core.runtime, org.eclipse.core.contenttype, + org.eclipse.core.resources, + org.eclipse.equinox.preferences, org.eclipse.tm4e.core, - com.hybris.hyeclipse.impex + com.hybris.hyeclipse.impex, + com.hybris.hyeclipse.impexed Automatic-Module-Name: com.hybris.hyeclipse.impex.tests diff --git a/com.hybris.hyeclipse.impex.tests/src/com/hybris/hyeclipse/impex/tests/ImpexFileCreatorTest.java b/com.hybris.hyeclipse.impex.tests/src/com/hybris/hyeclipse/impex/tests/ImpexFileCreatorTest.java new file mode 100644 index 00000000..c3393342 --- /dev/null +++ b/com.hybris.hyeclipse.impex.tests/src/com/hybris/hyeclipse/impex/tests/ImpexFileCreatorTest.java @@ -0,0 +1,185 @@ +/******************************************************************************* + * Copyright 2020 SAP + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + ******************************************************************************/ +package com.hybris.hyeclipse.impex.tests; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.UUID; + +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IFolder; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.ProjectScope; +import org.eclipse.core.resources.ResourceAttributes; +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.core.runtime.OperationCanceledException; +import org.eclipse.core.runtime.Path; +import org.eclipse.core.runtime.Platform; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import com.hybris.hyeclipse.impex.wizards.ImpexFileCreator; + +public class ImpexFileCreatorTest { + + private IProject project; + + @Before + public void createProject() throws Exception { + project = ResourcesPlugin.getWorkspace().getRoot().getProject("impex-test-" + UUID.randomUUID()); + project.create(null); + project.open(null); + } + + @After + public void deleteProject() throws Exception { + if (project != null && project.exists()) { + project.delete(true, true, null); + } + } + + @Test + public void validatesNamesAndExtensions() { + for (final String valid : new String[] {"test.impex", "test.IMPEX", "test.csv", "test.CSV", "é.impex"}) { + Assert.assertTrue(valid, ImpexFileCreator.validateFileName(valid).isOK()); + } + for (final String invalid : new String[] {null, "", "test", "test.txt", "../test.impex", "/test.impex", + "folder/test.impex", "folder\\test.impex"}) { + Assert.assertFalse(String.valueOf(invalid), ImpexFileCreator.validateFileName(invalid).isOK()); + } + } + + @Test + public void createsUtf8FileWithProjectLineDelimiter() throws Exception { + project.setDefaultCharset("UTF-16", null); + new ProjectScope(project).getNode(Platform.PI_RUNTIME).put(Platform.PREF_LINE_SEPARATOR, "\r\n"); + final IFile file = ImpexFileCreator.create(project, "é.impex", new NullProgressMonitor()); + Assert.assertTrue(file.exists()); + Assert.assertEquals("UTF-8", file.getCharset(false)); + final String contents = read(file); + Assert.assertTrue(contents.startsWith("# ")); + Assert.assertTrue(contents.endsWith("\r\n")); + Assert.assertEquals(1, contents.chars().filter(c -> c == '\n').count()); + Assert.assertFalse(contents.startsWith("\uFEFF")); + } + + @Test + public void createsFileInFolderAndAcceptsExplicitCsv() throws Exception { + final IFolder folder = project.getFolder("resources"); + folder.create(false, true, null); + new ProjectScope(project).getNode(Platform.PI_RUNTIME).put(Platform.PREF_LINE_SEPARATOR, "\n"); + final IFile file = ImpexFileCreator.create(folder, "sample.csv", new NullProgressMonitor()); + Assert.assertEquals(folder, file.getParent()); + Assert.assertTrue(read(file).endsWith("\n")); + Assert.assertFalse(read(file).contains("\r")); + } + + @Test + public void neverOverwritesExistingFile() throws Exception { + final IFile file = project.getFile("existing.impex"); + try (final ByteArrayInputStream stream = new ByteArrayInputStream("original".getBytes(StandardCharsets.UTF_8))) { + file.create(stream, false, null); + } + try { + ImpexFileCreator.create(project, file.getName(), new NullProgressMonitor()); + Assert.fail("Expected duplicate-file rejection"); + } catch (final CoreException expected) { + Assert.assertTrue(expected.getStatus().matches(IStatus.ERROR)); + } + Assert.assertEquals("original", read(file)); + } + + @Test + public void rejectsUntrackedLocalFileWithoutOverwritingIt() throws Exception { + final IFile file = project.getFile("untracked.impex"); + Files.writeString(file.getLocation().toFile().toPath(), "local original", StandardCharsets.UTF_8); + Assert.assertFalse(file.exists()); + try { + ImpexFileCreator.create(project, file.getName(), new NullProgressMonitor()); + Assert.fail("Expected local-file rejection"); + } catch (final CoreException expected) { + Assert.assertEquals("local original", Files.readString(file.getLocation().toFile().toPath())); + } + } + + @Test + public void cancellationDoesNotCreateFile() throws Exception { + final NullProgressMonitor monitor = new NullProgressMonitor(); + monitor.setCanceled(true); + try { + ImpexFileCreator.create(project, "cancelled.impex", monitor); + Assert.fail("Expected cancellation"); + } catch (final OperationCanceledException expected) { + Assert.assertFalse(project.getFile("cancelled.impex").exists()); + } + } + + @Test + public void rejectsClosedProject() throws Exception { + project.close(null); + try { + ImpexFileCreator.create(project, "closed.impex", new NullProgressMonitor()); + Assert.fail("Expected inaccessible-project rejection"); + } catch (final CoreException expected) { + Assert.assertFalse(project.getFile("closed.impex").exists()); + } + } + + @Test + public void rejectsReadOnlyFolder() throws Exception { + final IFolder folder = project.getFolder("readonly"); + folder.create(false, true, null); + final ResourceAttributes original = folder.getResourceAttributes(); + final ResourceAttributes readOnly = folder.getResourceAttributes(); + readOnly.setReadOnly(true); + folder.setResourceAttributes(readOnly); + try { + ImpexFileCreator.create(folder, "readonly.impex", new NullProgressMonitor()); + Assert.fail("Expected read-only-folder rejection"); + } catch (final CoreException expected) { + Assert.assertFalse(folder.getFile("readonly.impex").exists()); + } finally { + folder.setResourceAttributes(original); + } + } + + @Test + public void rejectsWorkspaceRootAndMissingFolder() throws Exception { + try { + ImpexFileCreator.create(ResourcesPlugin.getWorkspace().getRoot(), "root.impex", new NullProgressMonitor()); + Assert.fail("Expected workspace-root rejection"); + } catch (final CoreException expected) { + Assert.assertTrue(expected.getStatus().matches(IStatus.ERROR)); + } + try { + ImpexFileCreator.create(project.getFolder(new Path("missing")), "missing.impex", new NullProgressMonitor()); + Assert.fail("Expected missing-folder rejection"); + } catch (final CoreException expected) { + Assert.assertFalse(project.getFolder("missing").exists()); + } + } + + private String read(final IFile file) throws Exception { + try (final InputStream stream = file.getContents()) { + return new String(stream.readAllBytes(), StandardCharsets.UTF_8); + } + } +} diff --git a/com.hybris.hyeclipse.impex.tests/src/com/hybris/hyeclipse/impex/tests/ImpexRegistrationTest.java b/com.hybris.hyeclipse.impex.tests/src/com/hybris/hyeclipse/impex/tests/ImpexRegistrationTest.java index 7df0f804..33dde1f9 100644 --- a/com.hybris.hyeclipse.impex.tests/src/com/hybris/hyeclipse/impex/tests/ImpexRegistrationTest.java +++ b/com.hybris.hyeclipse.impex.tests/src/com/hybris/hyeclipse/impex/tests/ImpexRegistrationTest.java @@ -21,6 +21,43 @@ public class ImpexRegistrationTest { + @Test + public void replacementWizardOwnsTheExistingCommandAndShortcut() throws Exception { + final String id = "com.hybris.impexformatter.wizards.NewImpexWizard"; + int wizards = 0; + int commands = 0; + int bindings = 0; + for (final IConfigurationElement element : Platform.getExtensionRegistry() + .getConfigurationElementsFor("org.eclipse.ui.newWizards")) { + if (id.equals(element.getAttribute("id"))) { + Assert.assertEquals("com.hybris.hyeclipse.impex", element.getContributor().getName()); + Assert.assertNotNull(Platform.getBundle(element.getContributor().getName()) + .loadClass(element.getAttribute("class"))); + wizards++; + } + } + for (final IConfigurationElement element : Platform.getExtensionRegistry() + .getConfigurationElementsFor("org.eclipse.ui.commands")) { + if (id.equals(element.getAttribute("id"))) { + Assert.assertEquals("com.hybris.hyeclipse.impex", element.getContributor().getName()); + Assert.assertNotNull(Platform.getBundle(element.getContributor().getName()) + .loadClass(element.getAttribute("defaultHandler"))); + commands++; + } + } + for (final IConfigurationElement element : Platform.getExtensionRegistry() + .getConfigurationElementsFor("org.eclipse.ui.bindings")) { + if (id.equals(element.getAttribute("commandId"))) { + Assert.assertEquals("M1+Shift+Y", element.getAttribute("sequence")); + Assert.assertEquals("com.hybris.hyeclipse.impex", element.getContributor().getName()); + bindings++; + } + } + Assert.assertEquals(1, wizards); + Assert.assertEquals(1, commands); + Assert.assertEquals(1, bindings); + } + @Test public void recognizesImpexWithoutClaimingCsvFiles() { final IContentType type = Platform.getContentTypeManager() diff --git a/com.hybris.hyeclipse.impex/META-INF/MANIFEST.MF b/com.hybris.hyeclipse.impex/META-INF/MANIFEST.MF index 3c9a304c..0d78b766 100644 --- a/com.hybris.hyeclipse.impex/META-INF/MANIFEST.MF +++ b/com.hybris.hyeclipse.impex/META-INF/MANIFEST.MF @@ -7,7 +7,14 @@ Bundle-Vendor: SAP Bundle-RequiredExecutionEnvironment: JavaSE-21 Bundle-Localization: plugin Require-Bundle: org.eclipse.core.contenttype, + org.eclipse.core.resources, + org.eclipse.core.runtime, + org.eclipse.equinox.preferences, + org.eclipse.jface, + org.eclipse.ui, + org.eclipse.ui.ide, org.eclipse.ui.genericeditor, org.eclipse.tm4e.registry, org.eclipse.tm4e.ui Automatic-Module-Name: com.hybris.hyeclipse.impex +Export-Package: com.hybris.hyeclipse.impex.wizards diff --git a/com.hybris.hyeclipse.impex/README.md b/com.hybris.hyeclipse.impex/README.md index 2616fd81..3027c882 100644 --- a/com.hybris.hyeclipse.impex/README.md +++ b/com.hybris.hyeclipse.impex/README.md @@ -12,15 +12,24 @@ macros, data-cell strings, comments, and script directives have initial scopes; this is not a complete ImpEx parser. Backslash-continuation context and configurable header replacements still require further work. -Formatting, type-system completion/navigation, the new-file wizard, and LSP server -integration are not implemented yet. Use the legacy editor for those workflows. +Use **File > New > Other > SAP > New ImpEx File**, or **M1+Shift+Y**, to create +files with the replacement wizard. It uses the selected workspace project/folder, +refuses overwrites (including local files not yet refreshed into the workspace), +and opens the file in the preview. New files use UTF-8 and the project's configured +line delimiter. Explicit `.csv` names are accepted but currently open without +ImpEx highlighting. The old wizard/command registrations have been transferred +to this bundle without changing their IDs or duplicating the shortcut. + +Formatting, type-system completion/navigation, and LSP server integration are not +implemented yet. Use the legacy editor for formatting and completion workflows. Run the isolated OSGi tests: ```bash -./mvnw -pl com.hybris.hyeclipse.impex,com.hybris.hyeclipse.impex.tests -am verify +./mvnw -pl com.hybris.hyeclipse.commons,com.hybris.hyeclipse.impexed,com.hybris.hyeclipse.impex,com.hybris.hyeclipse.impex.tests -am verify ``` -The tests exercise the packaged grammar in TM4E and check extension registration -and class resolution. They do not replace interactive light/dark-theme and -existing-workspace upgrade testing. +Rebuild both editor bundles so registration tests do not use cached legacy metadata. +The tests exercise the packaged grammar, workspace file creation, and unique +wizard/command/shortcut registration. They do not replace interactive wizard, +light/dark-theme, and existing-workspace upgrade testing. diff --git a/com.hybris.hyeclipse.impex/build.properties b/com.hybris.hyeclipse.impex/build.properties index 7a84e960..243b7908 100644 --- a/com.hybris.hyeclipse.impex/build.properties +++ b/com.hybris.hyeclipse.impex/build.properties @@ -1,4 +1,6 @@ +source.. = src/ bin.includes = META-INF/,\ + .,\ plugin.xml,\ plugin.properties,\ syntaxes/ diff --git a/com.hybris.hyeclipse.impex/plugin.properties b/com.hybris.hyeclipse.impex/plugin.properties index 6f1bbe61..ae1c75b6 100644 --- a/com.hybris.hyeclipse.impex/plugin.properties +++ b/com.hybris.hyeclipse.impex/plugin.properties @@ -1,3 +1,7 @@ bundleName=SAP Commerce Cloud - ImpEx language support contentTypeName=ImpEx editorName=ImpEx Editor (Preview) +wizardName=New ImpEx File +wizardDescription=Create an ImpEx file and open it in the ImpEx editor preview. +sapCategoryName=SAP +commandCategoryName=ImpEx diff --git a/com.hybris.hyeclipse.impex/plugin.xml b/com.hybris.hyeclipse.impex/plugin.xml index ba920761..1c2f63bc 100644 --- a/com.hybris.hyeclipse.impex/plugin.xml +++ b/com.hybris.hyeclipse.impex/plugin.xml @@ -20,4 +20,21 @@ + + + + %wizardDescription + + + + + + + + + diff --git a/com.hybris.hyeclipse.impex/src/com/hybris/hyeclipse/impex/wizards/ImpexFileCreator.java b/com.hybris.hyeclipse.impex/src/com/hybris/hyeclipse/impex/wizards/ImpexFileCreator.java new file mode 100644 index 00000000..d9e33273 --- /dev/null +++ b/com.hybris.hyeclipse.impex/src/com/hybris/hyeclipse/impex/wizards/ImpexFileCreator.java @@ -0,0 +1,117 @@ +/******************************************************************************* + * Copyright 2020 SAP + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + ******************************************************************************/ +package com.hybris.hyeclipse.impex.wizards; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; + +import org.eclipse.core.resources.IContainer; +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.ProjectScope; +import org.eclipse.core.resources.ResourceAttributes; +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.OperationCanceledException; +import org.eclipse.core.runtime.Path; +import org.eclipse.core.runtime.Platform; +import org.eclipse.core.runtime.Status; +import org.eclipse.core.runtime.preferences.DefaultScope; +import org.eclipse.core.runtime.preferences.IScopeContext; +import org.eclipse.core.runtime.preferences.InstanceScope; + +/** Workspace-only file creation shared by the wizard and its integration tests. */ +public final class ImpexFileCreator { + + public static final String PLUGIN_ID = "com.hybris.hyeclipse.impex"; //$NON-NLS-1$ + public static final String EDITOR_ID = PLUGIN_ID + ".editor"; //$NON-NLS-1$ + public static final String DEFAULT_FILE_NAME = "test.impex"; //$NON-NLS-1$ + + private ImpexFileCreator() { + } + + /** + * Validates a single file name without modifying workspace resources. + * + * @param fileName the requested name, including its extension + * @return a status suitable for display by the wizard + */ + public static IStatus validateFileName(final String fileName) { + if (fileName == null || fileName.indexOf('/') >= 0 || fileName.indexOf('\\') >= 0) { + return new Status(IStatus.ERROR, PLUGIN_ID, Messages.invalidFileName); + } + final IStatus status = ResourcesPlugin.getWorkspace().validateName(fileName, IResource.FILE); + if (!status.isOK()) { + return status; + } + final String extension = new Path(fileName).getFileExtension(); + if (!"impex".equalsIgnoreCase(extension) && !"csv".equalsIgnoreCase(extension)) { //$NON-NLS-1$ //$NON-NLS-2$ + return new Status(IStatus.ERROR, PLUGIN_ID, Messages.invalidExtension); + } + return Status.OK_STATUS; + } + + /** + * Creates a UTF-8 file under a workspace scheduling rule. Existing files are never replaced. + * + * @param container an existing, accessible project or folder + * @param fileName a validated .impex or .csv name + * @param monitor progress and cancellation monitor + * @return the newly created file + * @throws CoreException if validation, file creation, or charset assignment fails + */ + public static IFile create(final IContainer container, final String fileName, + final IProgressMonitor monitor) throws CoreException { + final IStatus status = validateFileName(fileName); + if (!status.isOK()) { + throw new CoreException(status); + } + if (container == null || container.getType() == IResource.ROOT) { + throw error("An existing project or folder is required"); //$NON-NLS-1$ + } + final IFile file = container.getFile(new Path(fileName)); + // setCharset updates project-scoped metadata, requiring more than a folder creation rule. + container.getWorkspace().run(progress -> { + if (progress.isCanceled()) { + throw new OperationCanceledException(); + } + final ResourceAttributes attributes = container.getResourceAttributes(); + if (!container.isAccessible() || (attributes != null && attributes.isReadOnly())) { + throw error("The destination container is not accessible or is read-only"); //$NON-NLS-1$ + } + if (file.exists()) { + throw error("The destination file already exists"); //$NON-NLS-1$ + } + final String delimiter = Platform.getPreferencesService().getString(Platform.PI_RUNTIME, + Platform.PREF_LINE_SEPARATOR, System.lineSeparator(), new IScopeContext[] { + new ProjectScope(container.getProject()), InstanceScope.INSTANCE, DefaultScope.INSTANCE}); + final byte[] contents = (Messages.starterComment + delimiter).getBytes(StandardCharsets.UTF_8); + try (final ByteArrayInputStream stream = new ByteArrayInputStream(contents)) { + // force=false also protects a local file not yet known to the workspace. + file.create(stream, false, progress); + } catch (final IOException e) { + throw new CoreException(new Status(IStatus.ERROR, PLUGIN_ID, "Could not close file contents", e)); //$NON-NLS-1$ + } + file.setCharset(StandardCharsets.UTF_8.name(), progress); + }, container.getWorkspace().getRuleFactory().modifyRule(container.getProject()), IResource.NONE, monitor); + return file; + } + + private static CoreException error(final String message) { + return new CoreException(new Status(IStatus.ERROR, PLUGIN_ID, message)); + } +} diff --git a/com.hybris.hyeclipse.impex/src/com/hybris/hyeclipse/impex/wizards/Messages.java b/com.hybris.hyeclipse.impex/src/com/hybris/hyeclipse/impex/wizards/Messages.java new file mode 100644 index 00000000..e99fbd1c --- /dev/null +++ b/com.hybris.hyeclipse.impex/src/com/hybris/hyeclipse/impex/wizards/Messages.java @@ -0,0 +1,37 @@ +/******************************************************************************* + * Copyright 2020 SAP + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + ******************************************************************************/ +package com.hybris.hyeclipse.impex.wizards; + +import org.eclipse.osgi.util.NLS; + +final class Messages extends NLS { + + private static final String BUNDLE_NAME = "com.hybris.hyeclipse.impex.wizards.Messages"; //$NON-NLS-1$ + + public static String wizardTitle; + public static String wizardDescription; + public static String invalidExtension; + public static String invalidFileName; + public static String creatingFile; + public static String creationError; + public static String openingError; + public static String starterComment; + + static { + NLS.initializeMessages(BUNDLE_NAME, Messages.class); + } + + private Messages() { + } +} diff --git a/com.hybris.hyeclipse.impex/src/com/hybris/hyeclipse/impex/wizards/Messages.properties b/com.hybris.hyeclipse.impex/src/com/hybris/hyeclipse/impex/wizards/Messages.properties new file mode 100644 index 00000000..30842ee8 --- /dev/null +++ b/com.hybris.hyeclipse.impex/src/com/hybris/hyeclipse/impex/wizards/Messages.properties @@ -0,0 +1,8 @@ +wizardTitle=New ImpEx File +wizardDescription=Create an .impex file. Explicit .csv names are also accepted, but CSV files currently open without ImpEx highlighting. +invalidExtension=File extension must be .impex or .csv. +invalidFileName=Enter a single file name without a directory path. +creatingFile=Creating ImpEx file +creationError=Could not create the ImpEx file +openingError=The file was created but could not be opened +starterComment=# Use Ctrl+Space for content assist when ImpEx language services are available. diff --git a/com.hybris.hyeclipse.impex/src/com/hybris/hyeclipse/impex/wizards/NewImpexWizard.java b/com.hybris.hyeclipse.impex/src/com/hybris/hyeclipse/impex/wizards/NewImpexWizard.java new file mode 100644 index 00000000..a6b2f7ce --- /dev/null +++ b/com.hybris.hyeclipse.impex/src/com/hybris/hyeclipse/impex/wizards/NewImpexWizard.java @@ -0,0 +1,141 @@ +/******************************************************************************* + * Copyright 2020 SAP + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + ******************************************************************************/ +package com.hybris.hyeclipse.impex.wizards; + +import java.lang.reflect.InvocationTargetException; +import java.util.concurrent.atomic.AtomicReference; + +import org.eclipse.core.resources.IContainer; +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.OperationCanceledException; +import org.eclipse.core.runtime.Status; +import org.eclipse.jface.dialogs.ErrorDialog; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.jface.wizard.Wizard; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.ui.INewWizard; +import org.eclipse.ui.IWorkbench; +import org.eclipse.ui.IWorkbenchWindow; +import org.eclipse.ui.PartInitException; +import org.eclipse.ui.dialogs.WizardNewFileCreationPage; +import org.eclipse.ui.ide.IDE; +import org.eclipse.ui.wizards.newresource.BasicNewResourceWizard; + +/** Creates an ImpEx file without requiring a Commerce project or language server. */ +public final class NewImpexWizard extends Wizard implements INewWizard { + + private IWorkbench workbench; + private IStructuredSelection selection; + private WizardNewFileCreationPage page; + + /** Creates a wizard with background progress support. */ + public NewImpexWizard() { + setWindowTitle(Messages.wizardTitle); + setNeedsProgressMonitor(true); + } + + @Override + public void init(final IWorkbench workbench, final IStructuredSelection selection) { + this.workbench = workbench; + this.selection = selection; + } + + @Override + public void addPages() { + page = new WizardNewFileCreationPage("impexFile", selection) { //$NON-NLS-1$ + @Override + protected void createAdvancedControls(final Composite parent) { + // Linked/external file creation is intentionally outside this wizard's scope. + } + + @Override + protected IStatus validateLinkedResource() { + return Status.OK_STATUS; + } + + @Override + protected boolean validatePage() { + if (!super.validatePage()) { + return false; + } + final IStatus status = ImpexFileCreator.validateFileName(getFileName()); + if (!status.isOK()) { + setErrorMessage(status.getMessage()); + return false; + } + return true; + } + }; + page.setTitle(Messages.wizardTitle); + page.setDescription(Messages.wizardDescription); + page.setFileName(ImpexFileCreator.DEFAULT_FILE_NAME); + page.setAllowExistingResources(false); + addPage(page); + } + + @Override + public boolean performFinish() { + final IPath containerPath = page.getContainerFullPath(); + final String fileName = page.getFileName(); + final IResource resource = ResourcesPlugin.getWorkspace().getRoot().findMember(containerPath); + final IContainer destination = resource instanceof IContainer ? (IContainer) resource : null; + final AtomicReference result = new AtomicReference<>(); + try { + getContainer().run(true, true, monitor -> { + monitor.beginTask(Messages.creatingFile, 1); + try { + result.set(ImpexFileCreator.create(destination, fileName, monitor)); + } catch (final CoreException e) { + throw new InvocationTargetException(e); + } finally { + monitor.done(); + } + }); + } catch (final InterruptedException e) { + Thread.currentThread().interrupt(); + return false; + } catch (final InvocationTargetException e) { + final Throwable cause = e.getTargetException(); + if (cause instanceof OperationCanceledException) { + return false; + } + final IStatus status = cause instanceof CoreException ? ((CoreException) cause).getStatus() + : new Status(IStatus.ERROR, ImpexFileCreator.PLUGIN_ID, Messages.creationError, cause); + ErrorDialog.openError(getShell(), Messages.creationError, null, status); + return false; + } + final IFile file = result.get(); + if (file == null) { + return false; + } + final IWorkbenchWindow window = workbench.getActiveWorkbenchWindow(); + if (window != null) { + BasicNewResourceWizard.selectAndReveal(file, window); + } + if (window != null && window.getActivePage() != null) { + try { + IDE.openEditor(window.getActivePage(), file, ImpexFileCreator.EDITOR_ID, true); + } catch (final PartInitException e) { + // Creation succeeded; closing the wizard avoids accidentally trying to create the file again. + ErrorDialog.openError(getShell(), Messages.openingError, null, e.getStatus()); + } + } + return true; + } +} diff --git a/com.hybris.hyeclipse.impex/src/com/hybris/hyeclipse/impex/wizards/NewImpexWizardHandler.java b/com.hybris.hyeclipse.impex/src/com/hybris/hyeclipse/impex/wizards/NewImpexWizardHandler.java new file mode 100644 index 00000000..177c0559 --- /dev/null +++ b/com.hybris.hyeclipse.impex/src/com/hybris/hyeclipse/impex/wizards/NewImpexWizardHandler.java @@ -0,0 +1,40 @@ +/******************************************************************************* + * Copyright 2020 SAP + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + ******************************************************************************/ +package com.hybris.hyeclipse.impex.wizards; + +import org.eclipse.core.commands.AbstractHandler; +import org.eclipse.core.commands.ExecutionEvent; +import org.eclipse.core.commands.ExecutionException; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.jface.viewers.StructuredSelection; +import org.eclipse.jface.wizard.WizardDialog; +import org.eclipse.ui.IWorkbenchWindow; +import org.eclipse.ui.handlers.HandlerUtil; + +/** Opens the replacement wizard through the existing ImpEx wizard command. */ +public final class NewImpexWizardHandler extends AbstractHandler { + + @Override + public Object execute(final ExecutionEvent event) throws ExecutionException { + final IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event); + final ISelection selection = HandlerUtil.getCurrentSelection(event); + final IStructuredSelection structured = selection instanceof IStructuredSelection + ? (IStructuredSelection) selection : StructuredSelection.EMPTY; + final NewImpexWizard wizard = new NewImpexWizard(); + wizard.init(window.getWorkbench(), structured); + new WizardDialog(window.getShell(), wizard).open(); + return null; + } +} diff --git a/com.hybris.hyeclipse.impexed/plugin.xml b/com.hybris.hyeclipse.impexed/plugin.xml index 36851cef..ac8baa74 100755 --- a/com.hybris.hyeclipse.impexed/plugin.xml +++ b/com.hybris.hyeclipse.impexed/plugin.xml @@ -15,21 +15,6 @@ > - - - - - - - - - @@ -70,12 +49,6 @@ schemeId="org.eclipse.ui.defaultAcceleratorConfiguration" contextId="org.eclipse.ui.textEditorScope"> - - - \ No newline at end of file + diff --git a/docs/dev/impex/editor-replacement-plan.md b/docs/dev/impex/editor-replacement-plan.md index 6669da84..0fbb3dde 100644 --- a/docs/dev/impex/editor-replacement-plan.md +++ b/docs/dev/impex/editor-replacement-plan.md @@ -18,7 +18,16 @@ Status: migration started on `feature/impex-lsp-migration`; legacy editor retain - Verification: 9 new OSGi tests passed; the full 20-module package build passed with tests skipped after the isolated test run. The resulting p2 ZIP contains both editors and the packaged grammar. Interactive UI/upgrade checks remain. -- Next: continuation-aware lexical scanning, the new-file wizard, and LSP +- Added the new-file wizard using Eclipse's standard selection/validation page, + UTF-8 workspace creation, project line delimiters, cancellation, and overwrite + protection. Moved the old wizard/command/shortcut registrations to the new + bundle while retaining their IDs. CSV creation is supported; its content-type + override/highlighting remains a compatibility gap, explicitly described in the UI. +- Wizard verification: full reactor `verify` passed all 110 tests, including 19 + ImpEx grammar, registration, and workspace-creation tests. The p2 ZIP contains + the wizard and its NLS resources with no legacy wizard registration. Interactive + browsing, Java selection, shortcut execution, and editor-opening checks remain. +- Next: continuation-aware lexical scanning and LSP lifecycle, formatting, and project-scoped type-system services. These features are not implemented by the preview, and the legacy editor must not be retired. From e068b0f5d896547744df8549e592f97dc025ad3b Mon Sep 17 00:00:00 2001 From: Pawel Wolanski Date: Sat, 21 Nov 2026 03:00:06 +0100 Subject: [PATCH 04/25] feat(impex): add safe LSP formatting Align complete CSV blocks without rewriting values or scripts. Skip malformed, multiline, continued, and oversized inputs. Use in-process LSP4E transport with versioned document snapshots. Scope the legacy shortcut to prevent preview-editor conflicts. --- com.hybris.hyeclipse.feature/feature.xml | 7 + .../META-INF/MANIFEST.MF | 12 + com.hybris.hyeclipse.impex.ls/README.md | 31 +++ .../build.properties | 3 + com.hybris.hyeclipse.impex.ls/pom.xml | 14 ++ .../impex/ls/ImpexLanguageServer.java | 195 +++++++++++++++ .../impex/ls/format/ImpexCsvScanner.java | 191 +++++++++++++++ .../impex/ls/format/ImpexFormatter.java | 131 ++++++++++ .../impex/ls/format/TextPositions.java | 73 ++++++ .../META-INF/MANIFEST.MF | 5 + .../impex/tests/ImpexFormatterTest.java | 210 ++++++++++++++++ .../impex/tests/ImpexLanguageServerTest.java | 226 ++++++++++++++++++ .../impex/tests/ImpexRegistrationTest.java | 30 +++ .../META-INF/MANIFEST.MF | 9 +- com.hybris.hyeclipse.impex/README.md | 20 +- com.hybris.hyeclipse.impex/plugin.properties | 2 + com.hybris.hyeclipse.impex/plugin.xml | 17 ++ .../impex/lsp/ImpexConnectionProvider.java | 132 ++++++++++ com.hybris.hyeclipse.impexed/build.properties | 2 +- .../plugin.properties | 1 + com.hybris.hyeclipse.impexed/plugin.xml | 6 +- .../com/hybris/impexformatter/Activator.java | 1 + .../impexformatter/editors/ImpexEditor.java | 7 + docs/dev/impex/editor-replacement-plan.md | 18 +- pom.xml | 1 + 25 files changed, 1331 insertions(+), 13 deletions(-) create mode 100644 com.hybris.hyeclipse.impex.ls/META-INF/MANIFEST.MF create mode 100644 com.hybris.hyeclipse.impex.ls/README.md create mode 100644 com.hybris.hyeclipse.impex.ls/build.properties create mode 100644 com.hybris.hyeclipse.impex.ls/pom.xml create mode 100644 com.hybris.hyeclipse.impex.ls/src/com/hybris/hyeclipse/impex/ls/ImpexLanguageServer.java create mode 100644 com.hybris.hyeclipse.impex.ls/src/com/hybris/hyeclipse/impex/ls/format/ImpexCsvScanner.java create mode 100644 com.hybris.hyeclipse.impex.ls/src/com/hybris/hyeclipse/impex/ls/format/ImpexFormatter.java create mode 100644 com.hybris.hyeclipse.impex.ls/src/com/hybris/hyeclipse/impex/ls/format/TextPositions.java create mode 100644 com.hybris.hyeclipse.impex.tests/src/com/hybris/hyeclipse/impex/tests/ImpexFormatterTest.java create mode 100644 com.hybris.hyeclipse.impex.tests/src/com/hybris/hyeclipse/impex/tests/ImpexLanguageServerTest.java create mode 100644 com.hybris.hyeclipse.impex/src/com/hybris/hyeclipse/impex/lsp/ImpexConnectionProvider.java create mode 100644 com.hybris.hyeclipse.impexed/plugin.properties diff --git a/com.hybris.hyeclipse.feature/feature.xml b/com.hybris.hyeclipse.feature/feature.xml index 5081aabc..45522dc1 100755 --- a/com.hybris.hyeclipse.feature/feature.xml +++ b/com.hybris.hyeclipse.feature/feature.xml @@ -107,6 +107,13 @@ All rights reserved. version="0.0.0" unpack="false"/> + + + + 4.0.0 + + com.hybris.hyeclipse + com.hybris.hyeclipse.parent + 22.11.1-SNAPSHOT + + com.hybris.hyeclipse.impex.ls + eclipse-plugin + SAP Commerce Cloud - ImpEx language server + diff --git a/com.hybris.hyeclipse.impex.ls/src/com/hybris/hyeclipse/impex/ls/ImpexLanguageServer.java b/com.hybris.hyeclipse.impex.ls/src/com/hybris/hyeclipse/impex/ls/ImpexLanguageServer.java new file mode 100644 index 00000000..01970f96 --- /dev/null +++ b/com.hybris.hyeclipse.impex.ls/src/com/hybris/hyeclipse/impex/ls/ImpexLanguageServer.java @@ -0,0 +1,195 @@ +/******************************************************************************* + * Copyright 2020 SAP + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + ******************************************************************************/ +package com.hybris.hyeclipse.impex.ls; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +import org.eclipse.lsp4j.DidChangeConfigurationParams; +import org.eclipse.lsp4j.DidChangeTextDocumentParams; +import org.eclipse.lsp4j.DidChangeWatchedFilesParams; +import org.eclipse.lsp4j.DidCloseTextDocumentParams; +import org.eclipse.lsp4j.DidOpenTextDocumentParams; +import org.eclipse.lsp4j.DidSaveTextDocumentParams; +import org.eclipse.lsp4j.DocumentFormattingParams; +import org.eclipse.lsp4j.DocumentRangeFormattingParams; +import org.eclipse.lsp4j.InitializeParams; +import org.eclipse.lsp4j.InitializeResult; +import org.eclipse.lsp4j.PositionEncodingKind; +import org.eclipse.lsp4j.Range; +import org.eclipse.lsp4j.ServerCapabilities; +import org.eclipse.lsp4j.TextDocumentContentChangeEvent; +import org.eclipse.lsp4j.TextDocumentSyncKind; +import org.eclipse.lsp4j.TextEdit; +import org.eclipse.lsp4j.services.LanguageServer; +import org.eclipse.lsp4j.services.TextDocumentService; +import org.eclipse.lsp4j.services.WorkspaceService; + +import com.hybris.hyeclipse.impex.ls.format.ImpexFormatter; + +/** In-memory ImpEx formatting server; never reads files or executes ImpEx code. */ +public final class ImpexLanguageServer + implements LanguageServer, TextDocumentService, WorkspaceService, AutoCloseable { + + private static final int MAX_PENDING_REQUESTS = 8; + private final Map documents = new ConcurrentHashMap<>(); + private final Set>> pending = ConcurrentHashMap.newKeySet(); + private final ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1, 0, TimeUnit.MILLISECONDS, + new ArrayBlockingQueue<>(MAX_PENDING_REQUESTS), runnable -> { + final Thread thread = new Thread(runnable, "ImpEx formatting"); //$NON-NLS-1$ + thread.setDaemon(true); + return thread; + }); + private volatile boolean closed; + + private static final class DocumentSnapshot { + private final String text; + private final int version; + + private DocumentSnapshot(final String text, final int version) { + this.text = text; + this.version = version; + } + } + + @Override + public CompletableFuture initialize(final InitializeParams params) { + final ServerCapabilities capabilities = new ServerCapabilities(); + capabilities.setTextDocumentSync(TextDocumentSyncKind.Full); + capabilities.setPositionEncoding(PositionEncodingKind.UTF16); + capabilities.setDocumentFormattingProvider(true); + capabilities.setDocumentRangeFormattingProvider(true); + return CompletableFuture.completedFuture(new InitializeResult(capabilities)); + } + + @Override + public CompletableFuture shutdown() { + close(); + return CompletableFuture.completedFuture(null); + } + + @Override + public void exit() { + close(); + } + + @Override + public TextDocumentService getTextDocumentService() { + return this; + } + + @Override + public WorkspaceService getWorkspaceService() { + return this; + } + + @Override + public synchronized void didOpen(final DidOpenTextDocumentParams params) { + if (!closed) { + documents.put(params.getTextDocument().getUri(), new DocumentSnapshot(params.getTextDocument().getText(), + params.getTextDocument().getVersion())); + } + } + + @Override + public synchronized void didChange(final DidChangeTextDocumentParams params) { + final String uri = params.getTextDocument().getUri(); + final DocumentSnapshot previous = documents.get(uri); + final Integer version = params.getTextDocument().getVersion(); + if (closed || previous == null || version == null || version <= previous.version) { + return; + } + // Full synchronization is advertised; never format stale text after an unsupported ranged change. + for (final TextDocumentContentChangeEvent change : params.getContentChanges()) { + if (change.getRange() != null) { + documents.remove(uri); + return; + } + } + if (!params.getContentChanges().isEmpty()) { + documents.put(uri, new DocumentSnapshot(params.getContentChanges().getLast().getText(), version)); + } + } + + @Override + public synchronized void didClose(final DidCloseTextDocumentParams params) { + documents.remove(params.getTextDocument().getUri()); + } + + @Override + public void didSave(final DidSaveTextDocumentParams params) { + // Full document changes are authoritative; saving does not require disk access. + } + + @Override + public void didChangeConfiguration(final DidChangeConfigurationParams params) { + // Alignment has a fixed, whitespace-only policy in this first formatting slice. + } + + @Override + public void didChangeWatchedFiles(final DidChangeWatchedFilesParams params) { + // This server analyzes open document snapshots only. + } + + @Override + public CompletableFuture> formatting(final DocumentFormattingParams params) { + return format(params.getTextDocument().getUri(), null); + } + + @Override + public CompletableFuture> rangeFormatting(final DocumentRangeFormattingParams params) { + return format(params.getTextDocument().getUri(), params.getRange()); + } + + private synchronized CompletableFuture> format(final String uri, final Range range) { + final DocumentSnapshot snapshot = documents.get(uri); + if (closed || snapshot == null) { + return CompletableFuture.completedFuture(new ArrayList<>()); + } + final CompletableFuture> result = new CompletableFuture<>(); + pending.add(result); + result.whenComplete((value, error) -> pending.remove(result)); + try { + executor.execute(() -> { + try { + final List edits = new ImpexFormatter().format(snapshot.text, range, + () -> result.isCancelled() || closed || documents.get(uri) != snapshot); + synchronized (ImpexLanguageServer.this) { + result.complete(closed || documents.get(uri) != snapshot ? new ArrayList<>() : edits); + } + } catch (final RuntimeException e) { + result.completeExceptionally(e); + } + }); + } catch (final RejectedExecutionException e) { + result.completeExceptionally(e); + } + return result; + } + + /** Releases document state and cancels pending analysis when the connection stops. */ + @Override + public synchronized void close() { + closed = true; + documents.clear(); + for (final CompletableFuture> request : pending) { + request.cancel(true); + } + executor.shutdownNow(); + } +} diff --git a/com.hybris.hyeclipse.impex.ls/src/com/hybris/hyeclipse/impex/ls/format/ImpexCsvScanner.java b/com.hybris.hyeclipse.impex.ls/src/com/hybris/hyeclipse/impex/ls/format/ImpexCsvScanner.java new file mode 100644 index 00000000..e86a2783 --- /dev/null +++ b/com.hybris.hyeclipse.impex.ls/src/com/hybris/hyeclipse/impex/ls/format/ImpexCsvScanner.java @@ -0,0 +1,191 @@ +/******************************************************************************* + * Copyright 2020 SAP + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + ******************************************************************************/ +package com.hybris.hyeclipse.impex.ls.format; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.function.BooleanSupplier; +import java.util.regex.Pattern; + +/** Scans ImpEx cells without interpreting macros, headers, or executable code. */ +public final class ImpexCsvScanner { + + public static final int MAX_DOCUMENT_LENGTH = 4 * 1024 * 1024; + public static final int MAX_COLUMNS = 512; + private static final int MAX_RECORDS = 100_000; + private static final int CANCELLATION_INTERVAL = 4096; + private static final Pattern HEADER = Pattern.compile("(?i)^(INSERT_UPDATE|INSERT|UPDATE|REMOVE)\\s+\\S.*"); //$NON-NLS-1$ + + public enum Kind { + HEADER, DATA, COMMENT, SCRIPT, MACRO, BLANK, OTHER + } + + /** One logical CSV record, retaining its original source offsets and raw cells. */ + public static final class CsvRecord { + private final int start; + private final int contentEnd; + private final int end; + private final List cells; + private final boolean valid; + private final boolean multiline; + private final Kind kind; + + private CsvRecord(final int start, final int contentEnd, final int end, final List cells, + final boolean valid, final boolean multiline) { + this.start = start; + this.contentEnd = contentEnd; + this.end = end; + this.cells = Collections.unmodifiableList(new ArrayList<>(cells)); + this.valid = valid; + this.multiline = multiline; + final String first = valueOf(cells.get(0)); + if (first.startsWith("#%")) { //$NON-NLS-1$ + kind = Kind.SCRIPT; + } else if (first.startsWith("#")) { //$NON-NLS-1$ + kind = Kind.COMMENT; + } else if (first.startsWith("$") && first.contains("=")) { //$NON-NLS-1$ //$NON-NLS-2$ + kind = Kind.MACRO; + } else if (HEADER.matcher(first).matches()) { + kind = Kind.HEADER; + } else if (first.isEmpty() && cells.size() > 1) { + kind = Kind.DATA; + } else if (first.isEmpty() && cells.size() == 1) { + kind = Kind.BLANK; + } else { + kind = Kind.OTHER; + } + } + + /** @return inclusive source start */ + public int getStart() { return start; } + /** @return exclusive content end, before the final line delimiter */ + public int getContentEnd() { return contentEnd; } + /** @return exclusive record end, including its final line delimiter */ + public int getEnd() { return end; } + /** @return immutable raw cells, including empty and trailing cells */ + public List getCells() { return cells; } + /** @return whether quotes and text following closing quotes are valid */ + public boolean isValid() { return valid; } + /** @return whether quoted or backslash-continued lines were joined */ + public boolean isMultiline() { return multiline; } + /** @return lexical record kind */ + public Kind getKind() { return kind; } + } + + /** + * Extracts a cell value using doubled quotes and ImpEx edge trimming. + * Intended for valid, single-line cells; it does not expand macros. + * @param raw the original cell text + * @return the decoded, trimmed cell value + */ + public static String valueOf(final String raw) { + final String trimmed = raw.trim(); + if (trimmed.length() >= 2 && trimmed.startsWith("\"") && trimmed.endsWith("\"")) { //$NON-NLS-1$ //$NON-NLS-2$ + return trimmed.substring(1, trimmed.length() - 1).replace("\"\"", "\"").trim(); //$NON-NLS-1$ //$NON-NLS-2$ + } + return trimmed; + } + + /** + * @param source document text + * @return logical records preserving source boundaries + */ + public List scan(final String source) { + return scan(source, () -> false); + } + + /** + * Scans a bounded document. A quote opens quoting only before a cell has started; + * a doubled quote is literal, and a backslash never escapes a quote. + * @param source document text + * @param cancelled cancellation predicate + * @return logical records, or an empty list on cancellation + * @throws IllegalArgumentException when document/record/column limits are exceeded + */ + public List scan(final String source, final BooleanSupplier cancelled) { + if (source.length() > MAX_DOCUMENT_LENGTH) { + throw new IllegalArgumentException("ImpEx document exceeds the scanning limit"); //$NON-NLS-1$ + } + final List records = new ArrayList<>(); + List cells = new ArrayList<>(); + int recordStart = 0; + int cellStart = 0; + boolean quoted = false; + boolean cellStarted = false; + boolean cellEnded = false; + boolean valid = true; + boolean multiline = false; + for (int i = 0; i < source.length(); i++) { + if (i % CANCELLATION_INTERVAL == 0 && cancelled.getAsBoolean()) { + return new ArrayList<>(); + } + final char c = source.charAt(i); + if (c == '\r' || c == '\n') { + final int delimiterLength = c == '\r' && i + 1 < source.length() + && source.charAt(i + 1) == '\n' ? 2 : 1; + if (quoted || (i > recordStart && source.charAt(i - 1) == '\\')) { + multiline = true; + i += delimiterLength - 1; + continue; + } + cells.add(source.substring(cellStart, i)); + add(records, new CsvRecord(recordStart, i, i + delimiterLength, cells, valid, multiline)); + i += delimiterLength - 1; + recordStart = i + 1; + cellStart = recordStart; + cells = new ArrayList<>(); + cellStarted = false; + cellEnded = false; + valid = true; + multiline = false; + } else if (quoted) { + if (c == '"') { + if (i + 1 < source.length() && source.charAt(i + 1) == '"') { + i++; + } else { + quoted = false; + cellEnded = true; + } + } + } else if (c == ';') { + cells.add(source.substring(cellStart, i)); + if (cells.size() >= MAX_COLUMNS) { + throw new IllegalArgumentException("ImpEx record exceeds the column limit"); //$NON-NLS-1$ + } + cellStart = i + 1; + cellStarted = false; + cellEnded = false; + } else if (c == '"' && !cellStarted) { + quoted = true; + cellStarted = true; + } else if (!Character.isWhitespace(c)) { + if (cellEnded) { + valid = false; + } + cellStarted = true; + } + } + if (recordStart < source.length()) { + cells.add(source.substring(cellStart)); + // A final continuation marker without a following line is ambiguous to format. + valid = valid && !quoted && !source.endsWith("\\"); //$NON-NLS-1$ + add(records, new CsvRecord(recordStart, source.length(), source.length(), cells, valid, multiline)); + } + return records; + } + + private void add(final List records, final CsvRecord record) { + if (records.size() >= MAX_RECORDS) { + throw new IllegalArgumentException("ImpEx document exceeds the record limit"); //$NON-NLS-1$ + } + records.add(record); + } +} diff --git a/com.hybris.hyeclipse.impex.ls/src/com/hybris/hyeclipse/impex/ls/format/ImpexFormatter.java b/com.hybris.hyeclipse.impex.ls/src/com/hybris/hyeclipse/impex/ls/format/ImpexFormatter.java new file mode 100644 index 00000000..f93156ac --- /dev/null +++ b/com.hybris.hyeclipse.impex.ls/src/com/hybris/hyeclipse/impex/ls/format/ImpexFormatter.java @@ -0,0 +1,131 @@ +/******************************************************************************* + * Copyright 2020 SAP + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + ******************************************************************************/ +package com.hybris.hyeclipse.impex.ls.format; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.BooleanSupplier; + +import org.eclipse.lsp4j.Range; +import org.eclipse.lsp4j.TextEdit; + +import com.hybris.hyeclipse.impex.ls.format.ImpexCsvScanner.CsvRecord; +import com.hybris.hyeclipse.impex.ls.format.ImpexCsvScanner.Kind; + +/** Aligns complete, single-line header blocks using only safe CSV edge whitespace. */ +public final class ImpexFormatter { + + private static final int MAX_ALIGNMENT_WIDTH = 256; + + /** + * Formats the document, or complete blocks inside a selection. Scripts, comments, + * macros, line endings, and multiline/continued blocks are never rewritten. + * @param source immutable document text + * @param selection selection, or null for the full document + * @param cancelled cancellation/stale-result predicate + * @return non-overlapping source-ordered edits; empty on unsafe input or cancellation + */ + public List format(final String source, final Range selection, final BooleanSupplier cancelled) { + final List edits = new ArrayList<>(); + if (source.length() > ImpexCsvScanner.MAX_DOCUMENT_LENGTH || cancelled.getAsBoolean()) { + return edits; + } + final TextPositions positions = new TextPositions(source); + final int from; + final int to; + final List records; + try { + from = selection == null ? 0 : positions.offsetAt(selection.getStart()); + to = selection == null ? source.length() : positions.offsetAt(selection.getEnd()); + records = new ImpexCsvScanner().scan(source, cancelled); + } catch (final IllegalArgumentException e) { + return edits; + } + long outputLength = source.length(); + for (int first = 0; first < records.size(); first++) { + if (cancelled.getAsBoolean()) { + return new ArrayList<>(); + } + final CsvRecord header = records.get(first); + if (header.getKind() != Kind.HEADER) { + continue; + } + int end = first + 1; + while (end < records.size() && records.get(end).getKind() != Kind.HEADER) { + end++; + } + final List block = records.subList(first, end); + if (header.getStart() >= from && block.getLast().getContentEnd() <= to) { + final int[] widths = widths(block); + if (widths != null) { + for (final CsvRecord record : block) { + if (cancelled.getAsBoolean()) { + return new ArrayList<>(); + } + if (record.getKind() != Kind.HEADER && record.getKind() != Kind.DATA) { + continue; + } + final String replacement = align(record.getCells(), widths); + final String original = source.substring(record.getStart(), record.getContentEnd()); + outputLength += replacement.length() - original.length(); + if (outputLength > ImpexCsvScanner.MAX_DOCUMENT_LENGTH) { + return new ArrayList<>(); + } + if (!replacement.equals(original)) { + edits.add(new TextEdit(new Range(positions.positionAt(record.getStart()), + positions.positionAt(record.getContentEnd())), replacement)); + } + } + } + } + first = end - 1; + } + return cancelled.getAsBoolean() ? new ArrayList<>() : edits; + } + + private int[] widths(final List block) { + final int count = block.getFirst().getCells().size(); + if (count < 2) { + return null; + } + final int[] widths = new int[count]; + for (final CsvRecord record : block) { + if (!record.isValid() || record.getKind() == Kind.OTHER) { + return null; + } + if (record.getKind() != Kind.HEADER && record.getKind() != Kind.DATA) { + continue; + } + if (record.isMultiline() || record.getCells().size() != count) { + return null; + } + for (int i = 0; i < count; i++) { + final int length = record.getCells().get(i).trim().length(); + if (length > MAX_ALIGNMENT_WIDTH) { + return null; + } + widths[i] = Math.max(widths[i], length); + } + } + return widths; + } + + private String align(final List cells, final int[] widths) { + final StringBuilder result = new StringBuilder(); + for (int i = 0; i < cells.size(); i++) { + final String cell = cells.get(i).trim(); + result.append(cell); + if (i + 1 < cells.size()) { + result.append(" ".repeat(widths[i] - cell.length())).append("; "); //$NON-NLS-1$ //$NON-NLS-2$ + } + } + return result.toString(); + } +} diff --git a/com.hybris.hyeclipse.impex.ls/src/com/hybris/hyeclipse/impex/ls/format/TextPositions.java b/com.hybris.hyeclipse.impex.ls/src/com/hybris/hyeclipse/impex/ls/format/TextPositions.java new file mode 100644 index 00000000..88681e69 --- /dev/null +++ b/com.hybris.hyeclipse.impex.ls/src/com/hybris/hyeclipse/impex/ls/format/TextPositions.java @@ -0,0 +1,73 @@ +/******************************************************************************* + * Copyright 2020 SAP + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + ******************************************************************************/ +package com.hybris.hyeclipse.impex.ls.format; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.eclipse.lsp4j.Position; + +/** UTF-16 positions with CR, LF, and CRLF support for an immutable document snapshot. */ +public final class TextPositions { + + private final String text; + private final int[] starts; + + /** @param text immutable document text */ + public TextPositions(final String text) { + this.text = text; + final List offsets = new ArrayList<>(); + offsets.add(0); + for (int i = 0; i < text.length(); i++) { + if (text.charAt(i) == '\r') { + if (i + 1 < text.length() && text.charAt(i + 1) == '\n') { + i++; + } + offsets.add(i + 1); + } else if (text.charAt(i) == '\n') { + offsets.add(i + 1); + } + } + starts = offsets.stream().mapToInt(Integer::intValue).toArray(); + } + + /** + * @param position a valid UTF-16 position + * @return its source offset + */ + public int offsetAt(final Position position) { + if (position.getLine() < 0 || position.getLine() >= starts.length || position.getCharacter() < 0) { + throw new IllegalArgumentException("Invalid document position"); //$NON-NLS-1$ + } + final int start = starts[position.getLine()]; + int end = position.getLine() + 1 < starts.length ? starts[position.getLine() + 1] : text.length(); + while (end > start && (text.charAt(end - 1) == '\r' || text.charAt(end - 1) == '\n')) { + end--; + } + if (position.getCharacter() > end - start) { + throw new IllegalArgumentException("Document position extends past the line"); //$NON-NLS-1$ + } + return start + position.getCharacter(); + } + + /** + * @param offset a source offset + * @return its UTF-16 position + */ + public Position positionAt(final int offset) { + if (offset < 0 || offset > text.length()) { + throw new IllegalArgumentException("Invalid document offset"); //$NON-NLS-1$ + } + final int index = Arrays.binarySearch(starts, offset); + final int line = index >= 0 ? index : -index - 2; + return new Position(line, offset - starts[line]); + } +} diff --git a/com.hybris.hyeclipse.impex.tests/META-INF/MANIFEST.MF b/com.hybris.hyeclipse.impex.tests/META-INF/MANIFEST.MF index bf247505..18213cb6 100644 --- a/com.hybris.hyeclipse.impex.tests/META-INF/MANIFEST.MF +++ b/com.hybris.hyeclipse.impex.tests/META-INF/MANIFEST.MF @@ -11,6 +11,11 @@ Require-Bundle: org.junit, org.eclipse.core.resources, org.eclipse.equinox.preferences, org.eclipse.tm4e.core, + org.eclipse.text, + org.eclipse.lsp4j, + org.eclipse.lsp4j.jsonrpc, + org.eclipse.lsp4e, + com.hybris.hyeclipse.impex.ls, com.hybris.hyeclipse.impex, com.hybris.hyeclipse.impexed Automatic-Module-Name: com.hybris.hyeclipse.impex.tests diff --git a/com.hybris.hyeclipse.impex.tests/src/com/hybris/hyeclipse/impex/tests/ImpexFormatterTest.java b/com.hybris.hyeclipse.impex.tests/src/com/hybris/hyeclipse/impex/tests/ImpexFormatterTest.java new file mode 100644 index 00000000..58c1c7fc --- /dev/null +++ b/com.hybris.hyeclipse.impex.tests/src/com/hybris/hyeclipse/impex/tests/ImpexFormatterTest.java @@ -0,0 +1,210 @@ +/******************************************************************************* + * Copyright 2020 SAP + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + ******************************************************************************/ +package com.hybris.hyeclipse.impex.tests; + +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; + +import org.eclipse.lsp4j.Position; +import org.eclipse.lsp4j.Range; +import org.eclipse.lsp4j.TextEdit; +import org.junit.Assert; +import org.junit.Test; + +import com.hybris.hyeclipse.impex.ls.format.ImpexCsvScanner; +import com.hybris.hyeclipse.impex.ls.format.ImpexCsvScanner.CsvRecord; +import com.hybris.hyeclipse.impex.ls.format.ImpexCsvScanner.Kind; +import com.hybris.hyeclipse.impex.ls.format.ImpexFormatter; +import com.hybris.hyeclipse.impex.ls.format.TextPositions; + +public class ImpexFormatterTest { + + @Test + public void alignsCompleteBlocksAndIsIdempotent() { + final String source = "INSERT T;a;b\n;x;value\n;long;z"; + final String expected = "INSERT T; a ; b\n ; x ; value\n ; long; z"; + Assert.assertEquals(expected, format(source)); + Assert.assertEquals(expected, format(expected)); + Assert.assertTrue(new ImpexFormatter().format(expected, null, () -> false).isEmpty()); + assertSameValues(source, expected); + } + + @Test + public void preservesQuotesAndEmptyTrailingCells() { + final String source = "INSERT T;a;b;c\n;id;\" 5\"\" monitor; large \";\n;abc\"def;;"; + final String formatted = format(source); + Assert.assertNotEquals(source, formatted); + Assert.assertTrue(formatted.contains("\" 5\"\" monitor; large \"")); + assertSameValues(source, formatted); + } + + @Test + public void preservesScriptsCommentsAndMacroDefinitionsVerbatim() { + final String source = "$catalog=demo\n# comment\nINSERT T;a;b\n;id;value # literal\n" + + "\"#% beforeEach: line.clear();\"\n\"# quoted comment\";anything\n$other= untouched \n;long;x\n"; + final String formatted = format(source); + Assert.assertNotEquals(source, formatted); + for (final String preserved : new String[] {"$catalog=demo\n", "# comment\n", + "\"#% beforeEach: line.clear();\"\n", "\"# quoted comment\";anything\n", "$other= untouched \n"}) { + Assert.assertTrue(preserved, formatted.contains(preserved)); + } + assertSameValues(source, formatted); + } + + @Test + public void leavesMultilineAndBackslashContinuedBlocksUnchanged() { + for (final String source : new String[] { + "INSERT T;a;b\n;id;\"line1\nline2\"\n;other;value\n", + "INSERT T;a;b\r\n;id;part1\\\r\npart2\r\n;other;value\r\n", + "INSERT T;a;b\n;id;part1\\\nINSERT T;not;a;header\n"}) { + Assert.assertEquals(source, format(source)); + } + } + + @Test + public void refusesMalformedOrAmbiguousBlocks() { + for (final String source : new String[] { + "INSERT T;a;b\n;id;\"abc\"def\n", + "INSERT T;a;b\n;id;\"unclosed\n;other;x\n", + "INSERT T;a;b\n;id;\"5\\\" monitor\"\n", + "INSERT T;a;b\n;id\n", + "INSERT T;a;b\n;id;value;extra\n", + "INSERT T;a;b\nunknown line\n;id;x\n", + "INSERT T;a;b\n;id;unfinished\\"}) { + Assert.assertEquals(source, format(source)); + } + } + + @Test + public void canFormatValidBlockAfterMalformedRecord() { + final String unsafe = "INSERT T;a;b\n;id;\"abc\"def\n"; + final String safe = "INSERT T;a;b\n;long;x\n"; + Assert.assertEquals(unsafe + format(safe), format(unsafe + safe)); + } + + @Test + public void rangeFormattingDoesNotChangeUnselectedBlocks() { + final String first = "INSERT T;a;b\n;x;value\n"; + final String second = "UPDATE T;a;b\n;other;value\n"; + final String source = first + second; + final TextPositions positions = new TextPositions(source); + final Range selection = new Range(new Position(0, 0), positions.positionAt(first.length())); + final List edits = new ImpexFormatter().format(source, selection, () -> false); + Assert.assertEquals(format(first) + second, apply(source, edits)); + Assert.assertTrue(new ImpexFormatter().format(source, + new Range(new Position(1, 0), new Position(2, 0)), () -> false).isEmpty()); + Assert.assertTrue(new ImpexFormatter().format(source, + new Range(new Position(0, 0), new Position(0, 5)), () -> false).isEmpty()); + } + + @Test + public void preservesUnicodeMixedDelimitersAndFinalNewlineState() { + for (final String ending : new String[] {"", "\n", "\r\n"}) { + final String source = "INSERT T;a;b\r\n;id;é😀\r;long;value" + ending; + final String formatted = format(source); + assertSameValues(source, formatted); + Assert.assertEquals(source.replaceAll("[^\\r\\n]", ""), formatted.replaceAll("[^\\r\\n]", "")); + Assert.assertEquals(source.endsWith("\n"), formatted.endsWith("\n")); + } + } + + @Test + public void handlesNestedReferencesAndSpecialValuesWithoutExpansion() { + final String source = "INSERT_UPDATE T;a[unique=true];catalogVersion(catalog(id),version);b\n" + + ";$code;demo:Staged;(+?) one\n;id;demo:;\n"; + assertSameValues(source, format(source)); + } + + @Test + public void enforcesDocumentColumnAndAlignmentLimits() { + Assert.assertEquals("x".repeat(ImpexCsvScanner.MAX_DOCUMENT_LENGTH + 1), + format("x".repeat(ImpexCsvScanner.MAX_DOCUMENT_LENGTH + 1))); + final String wide = "INSERT T;a;b\n;id;" + "x".repeat(257); + Assert.assertEquals(wide, format(wide)); + final String manyColumns = "INSERT T" + ";a".repeat(ImpexCsvScanner.MAX_COLUMNS + 1); + Assert.assertEquals(manyColumns, format(manyColumns)); + } + + @Test + public void cancellationDiscardsAllEditsAndInvalidRangesAreSafe() { + final String source = "INSERT T;a;b\n;x;value\n".repeat(1000); + final AtomicInteger checks = new AtomicInteger(); + Assert.assertTrue(new ImpexFormatter().format(source, null, () -> checks.incrementAndGet() > 10).isEmpty()); + Assert.assertTrue(new ImpexFormatter().format(source, + new Range(new Position(0, 0), new Position(5000, 0)), () -> false).isEmpty()); + } + + @Test + public void scannerRecognizesCellQuotesAndLogicalRecordBoundaries() { + final String source = "INSERT T;a;b\r\n;id;\"a;\"\"b\nnext\"\r\n;id;abc\"def\r\n;id;x\\\r\ny\r\n"; + final List records = new ImpexCsvScanner().scan(source); + Assert.assertEquals(4, records.size()); + Assert.assertEquals(Kind.HEADER, records.get(0).getKind()); + Assert.assertTrue(records.get(1).isMultiline()); + Assert.assertEquals(3, records.get(1).getCells().size()); + Assert.assertFalse(records.get(2).isMultiline()); + Assert.assertTrue(records.get(2).isValid()); + Assert.assertTrue(records.get(3).isMultiline()); + int end = 0; + for (final CsvRecord record : records) { + Assert.assertEquals(end, record.getStart()); + end = record.getEnd(); + } + Assert.assertEquals(source.length(), end); + } + + @Test + public void positionsUseUtf16AndRejectOffsetsPastLineEnds() { + final TextPositions positions = new TextPositions("é😀B\r\nnext\rlast\n"); + Assert.assertEquals(3, positions.offsetAt(new Position(0, 3))); + Assert.assertEquals(new Position(0, 3), positions.positionAt(3)); + Assert.assertEquals(6, positions.offsetAt(new Position(1, 0))); + Assert.assertEquals(11, positions.offsetAt(new Position(2, 0))); + try { + positions.offsetAt(new Position(0, 5)); + Assert.fail("Expected invalid position"); + } catch (final IllegalArgumentException expected) { + Assert.assertNotNull(expected.getMessage()); + } + } + + private String format(final String source) { + return apply(source, new ImpexFormatter().format(source, null, () -> false)); + } + + private String apply(final String source, final List edits) { + final StringBuilder result = new StringBuilder(source); + final TextPositions positions = new TextPositions(source); + int nextStart = source.length(); + for (int i = edits.size() - 1; i >= 0; i--) { + final TextEdit edit = edits.get(i); + final int start = positions.offsetAt(edit.getRange().getStart()); + final int end = positions.offsetAt(edit.getRange().getEnd()); + Assert.assertTrue("Edits overlap", end <= nextStart); + result.replace(start, end, edit.getNewText()); + nextStart = start; + } + return result.toString(); + } + + private void assertSameValues(final String before, final String after) { + final List original = new ImpexCsvScanner().scan(before); + final List formatted = new ImpexCsvScanner().scan(after); + Assert.assertEquals(original.size(), formatted.size()); + for (int row = 0; row < original.size(); row++) { + Assert.assertEquals(original.get(row).getKind(), formatted.get(row).getKind()); + Assert.assertEquals(original.get(row).getCells().size(), formatted.get(row).getCells().size()); + for (int col = 0; col < original.get(row).getCells().size(); col++) { + Assert.assertEquals(ImpexCsvScanner.valueOf(original.get(row).getCells().get(col)), + ImpexCsvScanner.valueOf(formatted.get(row).getCells().get(col))); + } + } + } +} diff --git a/com.hybris.hyeclipse.impex.tests/src/com/hybris/hyeclipse/impex/tests/ImpexLanguageServerTest.java b/com.hybris.hyeclipse.impex.tests/src/com/hybris/hyeclipse/impex/tests/ImpexLanguageServerTest.java new file mode 100644 index 00000000..f592fe36 --- /dev/null +++ b/com.hybris.hyeclipse.impex.tests/src/com/hybris/hyeclipse/impex/tests/ImpexLanguageServerTest.java @@ -0,0 +1,226 @@ +/******************************************************************************* + * Copyright 2020 SAP + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + ******************************************************************************/ +package com.hybris.hyeclipse.impex.tests; + +import java.lang.reflect.Proxy; +import java.util.Arrays; +import java.util.ConcurrentModificationException; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; + +import org.eclipse.jface.text.Document; +import org.eclipse.lsp4e.VersionedEdits; +import org.eclipse.lsp4j.DidChangeTextDocumentParams; +import org.eclipse.lsp4j.DidCloseTextDocumentParams; +import org.eclipse.lsp4j.DidOpenTextDocumentParams; +import org.eclipse.lsp4j.DocumentFormattingParams; +import org.eclipse.lsp4j.DocumentRangeFormattingParams; +import org.eclipse.lsp4j.FormattingOptions; +import org.eclipse.lsp4j.InitializeParams; +import org.eclipse.lsp4j.Position; +import org.eclipse.lsp4j.Range; +import org.eclipse.lsp4j.ServerCapabilities; +import org.eclipse.lsp4j.TextDocumentContentChangeEvent; +import org.eclipse.lsp4j.TextDocumentIdentifier; +import org.eclipse.lsp4j.TextDocumentItem; +import org.eclipse.lsp4j.TextDocumentSyncKind; +import org.eclipse.lsp4j.TextEdit; +import org.eclipse.lsp4j.VersionedTextDocumentIdentifier; +import org.eclipse.lsp4j.jsonrpc.Launcher; +import org.eclipse.lsp4j.services.LanguageClient; +import org.eclipse.lsp4j.services.LanguageServer; +import org.eclipse.text.undo.DocumentUndoManagerRegistry; +import org.eclipse.text.undo.IDocumentUndoManager; +import org.junit.Assert; +import org.junit.Test; + +import com.hybris.hyeclipse.impex.ls.ImpexLanguageServer; +import com.hybris.hyeclipse.impex.lsp.ImpexConnectionProvider; + +public class ImpexLanguageServerTest { + + private static final String URI = "file:///impex-test.impex"; + private static final String SOURCE = "INSERT T;a;b\n;x;value\n"; + + @Test + public void lsp4eAppliesFormattingAsOneUndoableChange() throws Exception { + final Document document = new Document(SOURCE); + DocumentUndoManagerRegistry.connect(document); + final IDocumentUndoManager undo = DocumentUndoManagerRegistry.getDocumentUndoManager(document); + undo.connect(this); + try (final ImpexLanguageServer server = new ImpexLanguageServer()) { + open(server, 1, SOURCE); + final List edits = server.formatting(formatting()).get(); + new VersionedEdits(document.getModificationStamp(), edits, document).apply(); + final String formatted = document.get(); + Assert.assertNotEquals(SOURCE, formatted); + Assert.assertTrue(undo.undoable()); + undo.undo(); + Assert.assertEquals(SOURCE, document.get()); + Assert.assertFalse(undo.undoable()); + Assert.assertTrue(undo.redoable()); + undo.redo(); + Assert.assertEquals(formatted, document.get()); + } finally { + undo.disconnect(this); + DocumentUndoManagerRegistry.disconnect(document); + } + } + + @Test + public void lsp4eRejectsEditsWhenTheEditorDocumentChanged() throws Exception { + try (final ImpexLanguageServer server = new ImpexLanguageServer()) { + open(server, 1, SOURCE); + final Document document = new Document(SOURCE); + final VersionedEdits edits = new VersionedEdits(document.getModificationStamp(), + server.formatting(formatting()).get(), document); + document.replace(0, 0, "# subsequent edit\n"); + final String changed = document.get(); + try { + edits.apply(); + Assert.fail("Expected stale formatting rejection"); + } catch (final ConcurrentModificationException expected) { + Assert.assertEquals(changed, document.get()); + } + } + } + + @Test + public void advertisesOnlyImplementedServices() throws Exception { + try (final ImpexLanguageServer server = new ImpexLanguageServer()) { + final ServerCapabilities capabilities = server.initialize(new InitializeParams()).get().getCapabilities(); + Assert.assertEquals(TextDocumentSyncKind.Full, capabilities.getTextDocumentSync().getLeft()); + Assert.assertEquals("utf-16", capabilities.getPositionEncoding()); + Assert.assertTrue(capabilities.getDocumentFormattingProvider().getLeft()); + Assert.assertTrue(capabilities.getDocumentRangeFormattingProvider().getLeft()); + Assert.assertNull(capabilities.getCompletionProvider()); + Assert.assertNull(capabilities.getHoverProvider()); + Assert.assertNull(capabilities.getDocumentSymbolProvider()); + } + } + + @Test + public void formatsOpenSnapshotsAndNeverReadsUnopenedFiles() throws Exception { + try (final ImpexLanguageServer server = new ImpexLanguageServer()) { + Assert.assertTrue(server.formatting(formatting()).get().isEmpty()); + open(server, 1, SOURCE); + Assert.assertEquals(2, server.formatting(formatting()).get(5, TimeUnit.SECONDS).size()); + server.didClose(new DidCloseTextDocumentParams(new TextDocumentIdentifier(URI))); + Assert.assertTrue(server.formatting(formatting()).get().isEmpty()); + } + } + + @Test + public void fullChangesReplaceSnapshotsAndOldVersionsAreIgnored() throws Exception { + try (final ImpexLanguageServer server = new ImpexLanguageServer()) { + open(server, 1, SOURCE); + change(server, 3, "# replacement\n"); + change(server, 2, SOURCE); + Assert.assertTrue(server.formatting(formatting()).get().isEmpty()); + change(server, 4, SOURCE); + Assert.assertFalse(server.formatting(formatting()).get().isEmpty()); + } + } + + @Test + public void unsupportedRangedChangesCannotLeaveStaleFormattingState() throws Exception { + try (final ImpexLanguageServer server = new ImpexLanguageServer()) { + open(server, 1, SOURCE); + final TextDocumentContentChangeEvent change = new TextDocumentContentChangeEvent("new"); + change.setRange(new Range(new Position(0, 0), new Position(0, 1))); + server.didChange(new DidChangeTextDocumentParams(new VersionedTextDocumentIdentifier(URI, 2), + Arrays.asList(change))); + Assert.assertTrue(server.formatting(formatting()).get().isEmpty()); + } + } + + @Test + public void rangeRequestsRequireTheCompleteHeaderBlock() throws Exception { + try (final ImpexLanguageServer server = new ImpexLanguageServer()) { + open(server, 1, SOURCE); + final DocumentRangeFormattingParams partial = new DocumentRangeFormattingParams( + new TextDocumentIdentifier(URI), new FormattingOptions(4, true), + new Range(new Position(1, 0), new Position(2, 0))); + Assert.assertTrue(server.rangeFormatting(partial).get().isEmpty()); + partial.setRange(new Range(new Position(0, 0), new Position(2, 0))); + Assert.assertEquals(2, server.rangeFormatting(partial).get().size()); + } + } + + @Test + public void shutdownDropsDocumentsAndDoesNotExitTheHostJvm() throws Exception { + try (final ImpexLanguageServer server = new ImpexLanguageServer()) { + open(server, 1, SOURCE); + server.shutdown().get(); + server.exit(); + open(server, 2, SOURCE); + Assert.assertTrue(server.formatting(formatting()).get().isEmpty()); + } + } + + @Test + public void exchangesRealJsonRpcMessagesAndCanRestartConnection() throws Exception { + final ImpexConnectionProvider provider = new ImpexConnectionProvider(); + Assert.assertEquals(provider, new ImpexConnectionProvider()); + Assert.assertEquals(provider.hashCode(), new ImpexConnectionProvider().hashCode()); + for (int run = 0; run < 2; run++) { + final ExecutorService executor = Executors.newFixedThreadPool(2); + Future listening = null; + try { + provider.start(); + final LanguageClient client = (LanguageClient) Proxy.newProxyInstance(LanguageClient.class.getClassLoader(), + new Class[] {LanguageClient.class}, (proxy, method, args) -> + CompletableFuture.class.isAssignableFrom(method.getReturnType()) + ? CompletableFuture.completedFuture(null) : null); + final Launcher launcher = new Launcher.Builder() + .setLocalService(client).setRemoteInterface(LanguageServer.class) + .setInput(provider.getInputStream()).setOutput(provider.getOutputStream()) + .setExecutorService(executor).create(); + listening = launcher.startListening(); + final LanguageServer remote = launcher.getRemoteProxy(); + Assert.assertNotNull(remote.initialize(new InitializeParams()).get(5, TimeUnit.SECONDS)); + remote.getTextDocumentService().didOpen(new DidOpenTextDocumentParams( + new TextDocumentItem(URI, "impex", 1, SOURCE))); + final List edits = remote.getTextDocumentService().formatting(formatting()) + .get(5, TimeUnit.SECONDS); + Assert.assertEquals(2, edits.size()); + remote.shutdown().get(5, TimeUnit.SECONDS); + remote.exit(); + } finally { + if (listening != null) { + listening.cancel(true); + } + provider.stop(); + executor.shutdownNow(); + Assert.assertTrue(executor.awaitTermination(5, TimeUnit.SECONDS)); + } + Assert.assertNull(provider.getInputStream()); + Assert.assertNull(provider.getOutputStream()); + provider.stop(); + } + } + + private void open(final ImpexLanguageServer server, final int version, final String text) { + server.didOpen(new DidOpenTextDocumentParams(new TextDocumentItem(URI, "impex", version, text))); + } + + private void change(final ImpexLanguageServer server, final int version, final String text) { + server.didChange(new DidChangeTextDocumentParams(new VersionedTextDocumentIdentifier(URI, version), + Arrays.asList(new TextDocumentContentChangeEvent(text)))); + } + + private DocumentFormattingParams formatting() { + return new DocumentFormattingParams(new TextDocumentIdentifier(URI), new FormattingOptions(4, true)); + } +} diff --git a/com.hybris.hyeclipse.impex.tests/src/com/hybris/hyeclipse/impex/tests/ImpexRegistrationTest.java b/com.hybris.hyeclipse.impex.tests/src/com/hybris/hyeclipse/impex/tests/ImpexRegistrationTest.java index 33dde1f9..48215f41 100644 --- a/com.hybris.hyeclipse.impex.tests/src/com/hybris/hyeclipse/impex/tests/ImpexRegistrationTest.java +++ b/com.hybris.hyeclipse.impex.tests/src/com/hybris/hyeclipse/impex/tests/ImpexRegistrationTest.java @@ -21,6 +21,36 @@ public class ImpexRegistrationTest { + @Test + public void languageServerMappingAndLegacyFormatterScopeAreRegistered() throws Exception { + boolean mapping = false; + boolean server = false; + for (final IConfigurationElement element : Platform.getExtensionRegistry() + .getConfigurationElementsFor("org.eclipse.lsp4e.languageServer")) { + if ("com.hybris.hyeclipse.impex.languageServer".equals(element.getAttribute("id"))) { + if ("server".equals(element.getName())) { + Assert.assertNotNull(Platform.getBundle(element.getContributor().getName()) + .loadClass(element.getAttribute("class"))); + server = true; + } else if ("contentTypeMapping".equals(element.getName())) { + Assert.assertEquals("com.hybris.hyeclipse.impex.impex", element.getAttribute("contentType")); + Assert.assertEquals("impex", element.getAttribute("languageId")); + mapping = true; + } + } + } + Assert.assertTrue(server && mapping); + boolean scoped = false; + for (final IConfigurationElement element : Platform.getExtensionRegistry() + .getConfigurationElementsFor("org.eclipse.ui.bindings")) { + if ("impexFormatter".equals(element.getAttribute("commandId"))) { + Assert.assertEquals("com.hybris.hyeclipse.impexed.editorContext", element.getAttribute("contextId")); + scoped = true; + } + } + Assert.assertTrue(scoped); + } + @Test public void replacementWizardOwnsTheExistingCommandAndShortcut() throws Exception { final String id = "com.hybris.impexformatter.wizards.NewImpexWizard"; diff --git a/com.hybris.hyeclipse.impex/META-INF/MANIFEST.MF b/com.hybris.hyeclipse.impex/META-INF/MANIFEST.MF index 0d78b766..d5a61058 100644 --- a/com.hybris.hyeclipse.impex/META-INF/MANIFEST.MF +++ b/com.hybris.hyeclipse.impex/META-INF/MANIFEST.MF @@ -15,6 +15,11 @@ Require-Bundle: org.eclipse.core.contenttype, org.eclipse.ui.ide, org.eclipse.ui.genericeditor, org.eclipse.tm4e.registry, - org.eclipse.tm4e.ui + org.eclipse.tm4e.ui, + org.eclipse.lsp4e, + org.eclipse.lsp4j, + org.eclipse.lsp4j.jsonrpc, + com.hybris.hyeclipse.impex.ls Automatic-Module-Name: com.hybris.hyeclipse.impex -Export-Package: com.hybris.hyeclipse.impex.wizards +Export-Package: com.hybris.hyeclipse.impex.wizards, + com.hybris.hyeclipse.impex.lsp diff --git a/com.hybris.hyeclipse.impex/README.md b/com.hybris.hyeclipse.impex/README.md index 3027c882..b4acf2de 100644 --- a/com.hybris.hyeclipse.impex/README.md +++ b/com.hybris.hyeclipse.impex/README.md @@ -20,16 +20,24 @@ line delimiter. Explicit `.csv` names are accepted but currently open without ImpEx highlighting. The old wizard/command registrations have been transferred to this bundle without changing their IDs or duplicating the shortcut. -Formatting, type-system completion/navigation, and LSP server integration are not -implemented yet. Use the legacy editor for formatting and completion workflows. +The in-process language server now provides safe document/range formatting through +**Format ImpEx** or **M1+Shift+F**. Select a complete header block to format only that +block, or use the caret with no selection for document formatting. Multiline, +continued, malformed, or unsupported blocks are left unchanged. See the +[formatting policy](../com.hybris.hyeclipse.impex.ls/README.md) for limits and options. +The legacy formatter shortcut is scoped to its own editor to avoid interference. + +Type-system completion/navigation, macro assistance, symbols, and diagnostics are +not implemented yet. Use the legacy editor for type-system completion workflows. Run the isolated OSGi tests: ```bash -./mvnw -pl com.hybris.hyeclipse.commons,com.hybris.hyeclipse.impexed,com.hybris.hyeclipse.impex,com.hybris.hyeclipse.impex.tests -am verify +./mvnw -pl com.hybris.hyeclipse.commons,com.hybris.hyeclipse.impexed,com.hybris.hyeclipse.impex.ls,com.hybris.hyeclipse.impex,com.hybris.hyeclipse.impex.tests -am verify ``` Rebuild both editor bundles so registration tests do not use cached legacy metadata. -The tests exercise the packaged grammar, workspace file creation, and unique -wizard/command/shortcut registration. They do not replace interactive wizard, -light/dark-theme, and existing-workspace upgrade testing. +The tests exercise the packaged grammar, file creation, registration, formatting, +real JSON-RPC lifecycle, and LSP4E's stale-edit protection and document undo/redo. +They do not replace interactive shortcut, wizard, light/dark-theme, and +existing-workspace upgrade testing. diff --git a/com.hybris.hyeclipse.impex/plugin.properties b/com.hybris.hyeclipse.impex/plugin.properties index ae1c75b6..f9651705 100644 --- a/com.hybris.hyeclipse.impex/plugin.properties +++ b/com.hybris.hyeclipse.impex/plugin.properties @@ -5,3 +5,5 @@ wizardName=New ImpEx File wizardDescription=Create an ImpEx file and open it in the ImpEx editor preview. sapCategoryName=SAP commandCategoryName=ImpEx +languageServerName=ImpEx language server +formatName=Format ImpEx diff --git a/com.hybris.hyeclipse.impex/plugin.xml b/com.hybris.hyeclipse.impex/plugin.xml index 1c2f63bc..4f44ad2a 100644 --- a/com.hybris.hyeclipse.impex/plugin.xml +++ b/com.hybris.hyeclipse.impex/plugin.xml @@ -37,4 +37,21 @@ + + + + + + + + + + + + + + + diff --git a/com.hybris.hyeclipse.impex/src/com/hybris/hyeclipse/impex/lsp/ImpexConnectionProvider.java b/com.hybris.hyeclipse.impex/src/com/hybris/hyeclipse/impex/lsp/ImpexConnectionProvider.java new file mode 100644 index 00000000..a765e303 --- /dev/null +++ b/com.hybris.hyeclipse.impex/src/com/hybris/hyeclipse/impex/lsp/ImpexConnectionProvider.java @@ -0,0 +1,132 @@ +/******************************************************************************* + * Copyright 2020 SAP + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + ******************************************************************************/ +package com.hybris.hyeclipse.impex.lsp; + +import java.io.Closeable; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.PipedInputStream; +import java.io.PipedOutputStream; +import java.io.UncheckedIOException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +import org.eclipse.lsp4e.server.StreamConnectionProvider; +import org.eclipse.lsp4j.jsonrpc.Launcher; +import org.eclipse.lsp4j.services.LanguageClient; + +import com.hybris.hyeclipse.impex.ls.ImpexLanguageServer; + +/** Connects LSP4E to an in-process server without launching an external executable. */ +public final class ImpexConnectionProvider implements StreamConnectionProvider { + + private static final int PIPE_BUFFER_SIZE = 64 * 1024; + private PipedInputStream input; + private PipedOutputStream output; + private PipedInputStream serverInput; + private PipedOutputStream serverOutput; + private ImpexLanguageServer server; + private ExecutorService transport; + private Future listening; + + @Override + public synchronized void start() throws IOException { + if (server != null) { + return; + } + try { + input = new PipedInputStream(PIPE_BUFFER_SIZE); + serverOutput = new PipedOutputStream(input); + serverInput = new PipedInputStream(PIPE_BUFFER_SIZE); + output = new PipedOutputStream(serverInput); + server = new ImpexLanguageServer(); + transport = Executors.newFixedThreadPool(2, runnable -> { + final Thread thread = new Thread(runnable, "ImpEx LSP transport"); //$NON-NLS-1$ + thread.setDaemon(true); + return thread; + }); + final Launcher launcher = new Launcher.Builder() + .setLocalService(server).setRemoteInterface(LanguageClient.class) + .setInput(serverInput).setOutput(serverOutput).setExecutorService(transport).create(); + listening = launcher.startListening(); + } catch (final IOException | RuntimeException e) { + try { + stop(); + } catch (final RuntimeException cleanup) { + e.addSuppressed(cleanup); + } + throw new IOException("Could not start the ImpEx server connection", e); //$NON-NLS-1$ + } + } + + @Override + public synchronized InputStream getInputStream() { + return input; + } + + @Override + public synchronized OutputStream getOutputStream() { + return output; + } + + @Override + public InputStream getErrorStream() { + return null; + } + + @Override + public synchronized void stop() { + if (server != null) { + server.close(); + } + if (listening != null) { + listening.cancel(true); + } + IOException failure = null; + for (final Closeable stream : new Closeable[] {output, serverOutput, input, serverInput}) { + if (stream != null) { + try { + stream.close(); + } catch (final IOException e) { + if (failure == null) { + failure = e; + } else { + failure.addSuppressed(e); + } + } + } + } + if (transport != null) { + transport.shutdownNow(); + } + server = null; + input = null; + output = null; + serverInput = null; + serverOutput = null; + transport = null; + listening = null; + if (failure != null) { + throw new UncheckedIOException("Could not close the ImpEx server connection", failure); //$NON-NLS-1$ + } + } + + @Override + public boolean equals(final Object other) { + return other != null && getClass() == other.getClass(); + } + + @Override + public int hashCode() { + return getClass().hashCode(); + } +} diff --git a/com.hybris.hyeclipse.impexed/build.properties b/com.hybris.hyeclipse.impexed/build.properties index 05c961bd..962d8a96 100755 --- a/com.hybris.hyeclipse.impexed/build.properties +++ b/com.hybris.hyeclipse.impexed/build.properties @@ -1,7 +1,7 @@ source.. = src/ bin.includes = plugin.xml,\ + plugin.properties,\ META-INF/,\ .,\ icon/,\ .options - diff --git a/com.hybris.hyeclipse.impexed/plugin.properties b/com.hybris.hyeclipse.impexed/plugin.properties new file mode 100644 index 00000000..09e59161 --- /dev/null +++ b/com.hybris.hyeclipse.impexed/plugin.properties @@ -0,0 +1 @@ +legacyEditorContext=ImpEx legacy editor diff --git a/com.hybris.hyeclipse.impexed/plugin.xml b/com.hybris.hyeclipse.impexed/plugin.xml index ac8baa74..5f8d6b24 100755 --- a/com.hybris.hyeclipse.impexed/plugin.xml +++ b/com.hybris.hyeclipse.impexed/plugin.xml @@ -47,9 +47,13 @@ commandId="impexFormatter" sequence="M1+Shift+F" schemeId="org.eclipse.ui.defaultAcceleratorConfiguration" - contextId="org.eclipse.ui.textEditorScope"> + contextId="com.hybris.hyeclipse.impexed.editorContext"> + + + diff --git a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/Activator.java b/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/Activator.java index d8577e7b..76a6e2b8 100755 --- a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/Activator.java +++ b/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/Activator.java @@ -30,6 +30,7 @@ public class Activator extends AbstractUIPlugin { public static final String PLUGIN_ID = "com.hybris.hyeclipse.impexed"; //$NON-NLS-1$ public static final String IMPEX_PARTITIONING = "__impex_partitioning"; + public static final String EDITOR_CONTEXT_ID = PLUGIN_ID + ".editorContext"; //$NON-NLS-1$ // The shared instance private static Activator plugin; diff --git a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/editors/ImpexEditor.java b/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/editors/ImpexEditor.java index 9d9b288f..39871645 100755 --- a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/editors/ImpexEditor.java +++ b/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/editors/ImpexEditor.java @@ -20,6 +20,7 @@ //import org.eclipse.jface.text.source.IVerticalRuler; import org.eclipse.ui.editors.text.TextEditor; +import com.hybris.impexformatter.Activator; import com.hybris.impexformatter.DocumentProvider; public class ImpexEditor extends TextEditor { @@ -29,6 +30,12 @@ public ImpexEditor() { setSourceViewerConfiguration(new ImpexSourceViewerConfig(getPreferenceStore())); setDocumentProvider(new DocumentProvider()); } + + /** Keeps the legacy formatter shortcut local to this editor during migration. */ + @Override + protected void initializeKeyBindingScopes() { + setKeyBindingScopes(new String[] {Activator.EDITOR_CONTEXT_ID}); + } /*@Override protected IVerticalRuler createVerticalRuler() { diff --git a/docs/dev/impex/editor-replacement-plan.md b/docs/dev/impex/editor-replacement-plan.md index 0fbb3dde..c0c33023 100644 --- a/docs/dev/impex/editor-replacement-plan.md +++ b/docs/dev/impex/editor-replacement-plan.md @@ -27,9 +27,21 @@ Status: migration started on `feature/impex-lsp-migration`; legacy editor retain ImpEx grammar, registration, and workspace-creation tests. The p2 ZIP contains the wizard and its NLS resources with no legacy wizard registration. Interactive browsing, Java selection, shortcut execution, and editor-opening checks remain. -- Next: continuation-aware lexical scanning and LSP - lifecycle, formatting, and project-scoped type-system services. These features - are not implemented by the preview, and the legacy editor must not be retired. +- Added a non-UI `com.hybris.hyeclipse.impex.ls` bundle with cell-aware scanning, + safe document/range formatting, full document synchronization, and an in-process + LSP4E connection. The server advertises implemented capabilities only and never + reads server files or executes scripts. See its README for the fixed alignment + policy and safety/resource limits. +- Scoped the legacy formatter shortcut to its editor context; the preview uses + LSP4E's formatter action. Tests cover real JSON-RPC startup/restart/shutdown, + logical record boundaries, value preservation, UTF-16/ranges, cancellation, + and LSP4E's stale-edit rejection and compound document undo/redo. +- Formatting verification: all 133 tests passed in the full 21-module reactor, + including 42 ImpEx tests. The p2 ZIP contains both editor bundles, the language + server, and its connection provider. Live shortcut/focus and upgrade checks remain. +- Next: project-scoped type-system completion/navigation, macro assistance, + symbols/diagnostics, and interactive UI/upgrade checks. TextMate continuation + highlighting still needs refinement. The legacy editor must not be retired yet. ## Goal and scope diff --git a/pom.xml b/pom.xml index 53378b40..2b931dc7 100644 --- a/pom.xml +++ b/pom.xml @@ -51,6 +51,7 @@ com.hybris.hyeclipse.hac com.hybris.hyeclipse.impexed com.hybris.hyeclipse.impex + com.hybris.hyeclipse.impex.ls com.hybris.hyeclipse.impex.tests com.hybris.hyeclipse.importer com.hybris.hyeclipse.ytypesystem From 07b32b8e44b3bf1776c3c5b8c372ff1afbc3f3ea Mon Sep 17 00:00:00 2001 From: Pawel Wolanski Date: Sat, 21 Nov 2026 03:44:29 +0100 Subject: [PATCH 05/25] feat(impex): add scoped completion and navigation Reuse shared model snapshots through a workspace adapter. Resolve inherited and nested-reference attributes from indexed types. Reject unindexed roots and ambiguous models instead of global fallback. Keep the server UI-independent and discard stale requests. --- .../META-INF/MANIFEST.MF | 6 +- com.hybris.hyeclipse.impex.ls/README.md | 38 +- .../impex/ls/ImpexLanguageServer.java | 92 +++- .../impex/ls/types/ImpexLanguageFeatures.java | 407 ++++++++++++++++++ .../hyeclipse/impex/ls/types/Messages.java | 27 ++ .../impex/ls/types/Messages.properties | 5 + .../hyeclipse/impex/ls/types/TypeCatalog.java | 185 ++++++++ .../impex/ls/types/TypeSystemProvider.java | 34 ++ .../META-INF/MANIFEST.MF | 1 + .../impex/tests/ImpexCompletionTest.java | 201 +++++++++ .../impex/tests/ImpexLanguageServerTest.java | 10 +- .../impex/tests/ImpexTypeServiceTest.java | 156 +++++++ .../WorkspaceTypeSystemProviderTest.java | 188 ++++++++ .../META-INF/MANIFEST.MF | 1 + com.hybris.hyeclipse.impex/README.md | 19 +- .../impex/lsp/ImpexConnectionProvider.java | 2 +- .../lsp/WorkspaceTypeSystemProvider.java | 140 ++++++ docs/dev/impex/editor-replacement-plan.md | 17 +- 18 files changed, 1502 insertions(+), 27 deletions(-) create mode 100644 com.hybris.hyeclipse.impex.ls/src/com/hybris/hyeclipse/impex/ls/types/ImpexLanguageFeatures.java create mode 100644 com.hybris.hyeclipse.impex.ls/src/com/hybris/hyeclipse/impex/ls/types/Messages.java create mode 100644 com.hybris.hyeclipse.impex.ls/src/com/hybris/hyeclipse/impex/ls/types/Messages.properties create mode 100644 com.hybris.hyeclipse.impex.ls/src/com/hybris/hyeclipse/impex/ls/types/TypeCatalog.java create mode 100644 com.hybris.hyeclipse.impex.ls/src/com/hybris/hyeclipse/impex/ls/types/TypeSystemProvider.java create mode 100644 com.hybris.hyeclipse.impex.tests/src/com/hybris/hyeclipse/impex/tests/ImpexCompletionTest.java create mode 100644 com.hybris.hyeclipse.impex.tests/src/com/hybris/hyeclipse/impex/tests/ImpexTypeServiceTest.java create mode 100644 com.hybris.hyeclipse.impex.tests/src/com/hybris/hyeclipse/impex/tests/WorkspaceTypeSystemProviderTest.java create mode 100644 com.hybris.hyeclipse.impex/src/com/hybris/hyeclipse/impex/lsp/WorkspaceTypeSystemProvider.java diff --git a/com.hybris.hyeclipse.impex.ls/META-INF/MANIFEST.MF b/com.hybris.hyeclipse.impex.ls/META-INF/MANIFEST.MF index d79cab5e..09a756e4 100644 --- a/com.hybris.hyeclipse.impex.ls/META-INF/MANIFEST.MF +++ b/com.hybris.hyeclipse.impex.ls/META-INF/MANIFEST.MF @@ -6,7 +6,9 @@ Bundle-Version: 22.11.1.qualifier Bundle-Vendor: SAP Bundle-RequiredExecutionEnvironment: JavaSE-21 Require-Bundle: org.eclipse.lsp4j, - org.eclipse.lsp4j.jsonrpc + org.eclipse.lsp4j.jsonrpc, + org.eclipse.osgi Export-Package: com.hybris.hyeclipse.impex.ls, - com.hybris.hyeclipse.impex.ls.format + com.hybris.hyeclipse.impex.ls.format, + com.hybris.hyeclipse.impex.ls.types Automatic-Module-Name: com.hybris.hyeclipse.impex.ls diff --git a/com.hybris.hyeclipse.impex.ls/README.md b/com.hybris.hyeclipse.impex.ls/README.md index 73234204..457f7adc 100644 --- a/com.hybris.hyeclipse.impex.ls/README.md +++ b/com.hybris.hyeclipse.impex.ls/README.md @@ -1,9 +1,35 @@ # ImpEx language server Non-UI LSP4J bundle, connected in-process through the preview bundle's LSP4E -provider. Only full document synchronization, UTF-16 positions, document formatting, -and range formatting are currently advertised. The server analyzes open snapshots; -it does not load files, connect to Commerce, or execute scripts. +provider. Full document synchronization, UTF-16 positions, document/range formatting, +completion, and definition navigation are advertised. The server analyzes open +snapshots and host-supplied metadata; it does not load files, connect to Commerce, +or execute scripts. + +## Completion and navigation policy + +- Context-specific operation/type names, inherited attributes, nested/collection + references, explicit type paths, header/column modifiers, boolean/collection-mode + values, and earlier document-local macro definitions. +- Proposals replace only the current token, including its suffix when typing in + the middle. At most 200 proposals are returned; truncated lists are marked + incomplete so a refined prefix can request a narrower result. +- Reference types come from indexed accessor Java types; ambiguous model names + are not resolved by guessing or stripping a `Model` suffix. +- `TypeSystemProvider` is the host boundary. The Eclipse adapter reuses immutable + `TypeSystemSnapshot` data and caches its DTO projection until the snapshot changes. + Source accessibility and URI are resolved by the host when navigation is requested. +- The current shared index supports one project named `platform`. Its standard + `bin/platform` layout scopes the wider Commerce tree; nonstandard layouts scope + only the platform project's own directory. Unindexed roots, external extensions, + closed projects, and ambiguous workspace aliases receive no indexed proposals. + Do not treat this as full multi-platform indexing support. +- Unknown types and missing indexes retain syntax/modifier/macro proposals without + speculative attributes or false validation errors. Comments/scripts do not get + type/macro assistance. Quoted/continued or macro-expanded headers remain unsupported + for type-context resolution. +- Metadata lookups run on the bounded analysis worker. Document or index changes + during a request discard obsolete proposals; shutdown cancels pending requests. ## Formatting policy @@ -18,7 +44,7 @@ it does not load files, connect to Commerce, or execute scripts. - Bounds: 4 Mi UTF-16 code units per input/output document, 100,000 logical records, 512 cells per record, and 256 UTF-16 code units per aligned cell. Oversized/unsafe input produces no edits, rather than attempting potentially destructive recovery. -- Formatting uses a single background worker with at most eight queued requests. +- Language analysis uses a single background worker with at most eight queued requests. Closed, superseded, or cancelled requests cannot supply edits for old snapshots. LSP4E also rejects results when the editor document's modification stamp changed. @@ -27,5 +53,5 @@ at cell boundaries, doubled quotes are literal, and backslashes do not escape qu The scanner groups continued/multiline records for safety, but does not implement the full import engine or header execution semantics. -Type-system completion/navigation, macro assistance, symbols, and diagnostics are -subsequent slices. See [the migration plan](../docs/dev/impex/editor-replacement-plan.md). +Macro hover, symbols, diagnostics, and UI/upgrade checks are subsequent slices. +See [the migration plan](../docs/dev/impex/editor-replacement-plan.md). diff --git a/com.hybris.hyeclipse.impex.ls/src/com/hybris/hyeclipse/impex/ls/ImpexLanguageServer.java b/com.hybris.hyeclipse.impex.ls/src/com/hybris/hyeclipse/impex/ls/ImpexLanguageServer.java index 01970f96..fd71da5f 100644 --- a/com.hybris.hyeclipse.impex.ls/src/com/hybris/hyeclipse/impex/ls/ImpexLanguageServer.java +++ b/com.hybris.hyeclipse.impex.ls/src/com/hybris/hyeclipse/impex/ls/ImpexLanguageServer.java @@ -10,6 +10,7 @@ package com.hybris.hyeclipse.impex.ls; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Set; @@ -19,7 +20,14 @@ import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; +import java.util.function.BiFunction; +import java.util.function.BooleanSupplier; +import org.eclipse.lsp4j.CompletionItem; +import org.eclipse.lsp4j.CompletionList; +import org.eclipse.lsp4j.CompletionOptions; +import org.eclipse.lsp4j.CompletionParams; +import org.eclipse.lsp4j.DefinitionParams; import org.eclipse.lsp4j.DidChangeConfigurationParams; import org.eclipse.lsp4j.DidChangeTextDocumentParams; import org.eclipse.lsp4j.DidChangeWatchedFilesParams; @@ -30,33 +38,50 @@ import org.eclipse.lsp4j.DocumentRangeFormattingParams; import org.eclipse.lsp4j.InitializeParams; import org.eclipse.lsp4j.InitializeResult; +import org.eclipse.lsp4j.Location; +import org.eclipse.lsp4j.LocationLink; import org.eclipse.lsp4j.PositionEncodingKind; -import org.eclipse.lsp4j.Range; import org.eclipse.lsp4j.ServerCapabilities; import org.eclipse.lsp4j.TextDocumentContentChangeEvent; import org.eclipse.lsp4j.TextDocumentSyncKind; import org.eclipse.lsp4j.TextEdit; +import org.eclipse.lsp4j.jsonrpc.messages.Either; import org.eclipse.lsp4j.services.LanguageServer; import org.eclipse.lsp4j.services.TextDocumentService; import org.eclipse.lsp4j.services.WorkspaceService; import com.hybris.hyeclipse.impex.ls.format.ImpexFormatter; +import com.hybris.hyeclipse.impex.ls.types.ImpexLanguageFeatures; +import com.hybris.hyeclipse.impex.ls.types.ImpexLanguageFeatures.SourceTarget; +import com.hybris.hyeclipse.impex.ls.types.TypeCatalog; +import com.hybris.hyeclipse.impex.ls.types.TypeSystemProvider; -/** In-memory ImpEx formatting server; never reads files or executes ImpEx code. */ +/** In-memory ImpEx language services; host metadata is supplied through a non-UI adapter boundary. */ public final class ImpexLanguageServer implements LanguageServer, TextDocumentService, WorkspaceService, AutoCloseable { private static final int MAX_PENDING_REQUESTS = 8; private final Map documents = new ConcurrentHashMap<>(); - private final Set>> pending = ConcurrentHashMap.newKeySet(); + private final Set> pending = ConcurrentHashMap.newKeySet(); + private final TypeSystemProvider types; private final ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1, 0, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(MAX_PENDING_REQUESTS), runnable -> { - final Thread thread = new Thread(runnable, "ImpEx formatting"); //$NON-NLS-1$ + final Thread thread = new Thread(runnable, "ImpEx language analysis"); //$NON-NLS-1$ thread.setDaemon(true); return thread; }); private volatile boolean closed; + /** Creates syntax-only services for hosts without a type-system adapter. */ + public ImpexLanguageServer() { + this(uri -> TypeCatalog.empty()); + } + + /** @param types document-scoped metadata provider, queried only on the analysis worker */ + public ImpexLanguageServer(final TypeSystemProvider types) { + this.types = types; + } + private static final class DocumentSnapshot { private final String text; private final int version; @@ -74,6 +99,9 @@ public CompletableFuture initialize(final InitializeParams par capabilities.setPositionEncoding(PositionEncodingKind.UTF16); capabilities.setDocumentFormattingProvider(true); capabilities.setDocumentRangeFormattingProvider(true); + capabilities.setCompletionProvider(new CompletionOptions(false, + Arrays.asList(";", "(", "[", ",", ".", "$", "="))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ + capabilities.setDefinitionProvider(true); return CompletableFuture.completedFuture(new InitializeResult(capabilities)); } @@ -148,29 +176,69 @@ public void didChangeWatchedFiles(final DidChangeWatchedFilesParams params) { @Override public CompletableFuture> formatting(final DocumentFormattingParams params) { - return format(params.getTextDocument().getUri(), null); + return request(params.getTextDocument().getUri(), new ArrayList<>(), + (snapshot, cancelled) -> new ImpexFormatter().format(snapshot.text, null, cancelled)); } @Override public CompletableFuture> rangeFormatting(final DocumentRangeFormattingParams params) { - return format(params.getTextDocument().getUri(), params.getRange()); + return request(params.getTextDocument().getUri(), new ArrayList<>(), + (snapshot, cancelled) -> new ImpexFormatter().format(snapshot.text, params.getRange(), cancelled)); + } + + @Override + public CompletableFuture, CompletionList>> completion(final CompletionParams params) { + final String uri = params.getTextDocument().getUri(); + return request(uri, completionReply(ImpexLanguageFeatures.emptyCompletion()), (snapshot, cancelled) -> { + final TypeCatalog catalog = types.getCatalog(uri); + final CompletionList proposals = new ImpexLanguageFeatures().complete(snapshot.text, params.getPosition(), + catalog, cancelled); + return completionReply(types.getCatalog(uri) == catalog ? proposals : ImpexLanguageFeatures.emptyCompletion()); + }); + } + + @Override + public CompletableFuture, List>> definition( + final DefinitionParams params) { + final String uri = params.getTextDocument().getUri(); + return request(uri, definitionReply(new ArrayList<>()), (snapshot, cancelled) -> { + final TypeCatalog catalog = types.getCatalog(uri); + final SourceTarget target = new ImpexLanguageFeatures().definition(snapshot.text, params.getPosition(), catalog); + final List locations = new ArrayList<>(); + if (target != null && !cancelled.getAsBoolean() && types.getCatalog(uri) == catalog) { + final Location location = types.resolveLocation(uri, target.getPath(), target.getLine()); + if (location != null) { + locations.add(location); + } + } + return definitionReply(locations); + }); + } + + private Either, CompletionList> completionReply(final CompletionList list) { + return Either.forRight(list); + } + + private Either, List> definitionReply(final List locations) { + return Either.forLeft(locations); } - private synchronized CompletableFuture> format(final String uri, final Range range) { + private synchronized CompletableFuture request(final String uri, final T empty, + final BiFunction analyze) { final DocumentSnapshot snapshot = documents.get(uri); if (closed || snapshot == null) { - return CompletableFuture.completedFuture(new ArrayList<>()); + return CompletableFuture.completedFuture(empty); } - final CompletableFuture> result = new CompletableFuture<>(); + final CompletableFuture result = new CompletableFuture<>(); pending.add(result); result.whenComplete((value, error) -> pending.remove(result)); try { executor.execute(() -> { try { - final List edits = new ImpexFormatter().format(snapshot.text, range, + final T value = analyze.apply(snapshot, () -> result.isCancelled() || closed || documents.get(uri) != snapshot); synchronized (ImpexLanguageServer.this) { - result.complete(closed || documents.get(uri) != snapshot ? new ArrayList<>() : edits); + result.complete(closed || documents.get(uri) != snapshot ? empty : value); } } catch (final RuntimeException e) { result.completeExceptionally(e); @@ -187,7 +255,7 @@ private synchronized CompletableFuture> format(final St public synchronized void close() { closed = true; documents.clear(); - for (final CompletableFuture> request : pending) { + for (final CompletableFuture request : pending) { request.cancel(true); } executor.shutdownNow(); diff --git a/com.hybris.hyeclipse.impex.ls/src/com/hybris/hyeclipse/impex/ls/types/ImpexLanguageFeatures.java b/com.hybris.hyeclipse.impex.ls/src/com/hybris/hyeclipse/impex/ls/types/ImpexLanguageFeatures.java new file mode 100644 index 00000000..b050f841 --- /dev/null +++ b/com.hybris.hyeclipse.impex.ls/src/com/hybris/hyeclipse/impex/ls/types/ImpexLanguageFeatures.java @@ -0,0 +1,407 @@ +/******************************************************************************* + * Copyright 2020 SAP + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + ******************************************************************************/ +package com.hybris.hyeclipse.impex.ls.types; + +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Deque; +import java.util.List; +import java.util.Set; +import java.util.TreeSet; +import java.util.function.BooleanSupplier; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.eclipse.lsp4j.CompletionItem; +import org.eclipse.lsp4j.CompletionItemKind; +import org.eclipse.lsp4j.CompletionList; +import org.eclipse.lsp4j.Position; +import org.eclipse.lsp4j.Range; +import org.eclipse.lsp4j.TextEdit; +import org.eclipse.lsp4j.jsonrpc.messages.Either; + +import com.hybris.hyeclipse.impex.ls.format.ImpexCsvScanner; +import com.hybris.hyeclipse.impex.ls.format.ImpexCsvScanner.CsvRecord; +import com.hybris.hyeclipse.impex.ls.format.ImpexCsvScanner.Kind; +import com.hybris.hyeclipse.impex.ls.format.TextPositions; +import com.hybris.hyeclipse.impex.ls.types.TypeCatalog.Attribute; +import com.hybris.hyeclipse.impex.ls.types.TypeCatalog.Type; + +/** Conservative header-context assistance using indexed metadata, not runtime import semantics. */ +public final class ImpexLanguageFeatures { + + private static final int MAX_PROPOSALS = 200; + private static final Pattern MODE = Pattern.compile("(?i)^\\s*(INSERT_UPDATE|INSERT|UPDATE|REMOVE)(?:\\s+|$)"); //$NON-NLS-1$ + private static final Pattern MACRO = Pattern.compile("^\\s*(\\$[\\w-]+)\\s*="); //$NON-NLS-1$ + private static final List OPERATIONS = Arrays.asList("INSERT", "INSERT_UPDATE", "REMOVE", "UPDATE"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + private static final List HEADER_MODIFIERS = Arrays.asList("batchmode", "cacheUnique", "processor", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + "parallel", "ignoreKeyCase", "unlessExisting", "impex.legacy.mode", "sld.enabled", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ + "disable.interceptor.types", "disable.interceptor.beans", "disable.UniqueAttributesValidator.for.types", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + "testMode"); //$NON-NLS-1$ + private static final List COLUMN_MODIFIERS = Arrays.asList("unique", "allownull", "ignorenull", "default", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + "virtual", "lang", "translator", "cellDecorator", "dateformat", "numberformat", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ + "collection-delimiter", "path-delimiter", "key2value-delimiter", "map-delimiter", "mode", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ + "query-chunk-size", "forceWrite", "pos", "alias", "sourceSystemId", "pkFromExternalImportKey"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ + private static final List BOOLEAN_MODIFIERS = Arrays.asList("unique", "allownull", "ignorenull", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + "virtual", "forceWrite", "pkFromExternalImportKey", "batchmode", "cacheUnique", "parallel", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ + "ignoreKeyCase", "unlessExisting", "impex.legacy.mode", "sld.enabled", "testMode"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ + + private enum Area { NONE, OPERATION, TYPE, ATTRIBUTE, MODIFIER, VALUE, MACRO } + + /** Provider-specific declaration identity; the host resolves accessibility and URI. */ + public static final class SourceTarget { + private final String path; + private final int line; + + private SourceTarget(final String path, final int line) { + this.path = path; + this.line = line; + } + /** @return provider-specific source path */ + public String getPath() { return path; } + /** @return one-based declaration line */ + public int getLine() { return line; } + } + + private static final class Token { + private final int start; + private final int end; + private final String text; + private final String prefix; + + private Token(final String source, final int offset, final boolean dots) { + int from = offset; + int to = offset; + while (from > 0 && nameChar(source.charAt(from - 1), dots)) { + from--; + } + while (to < source.length() && nameChar(source.charAt(to), dots)) { + to++; + } + start = from; + end = to; + text = source.substring(from, to); + prefix = source.substring(from, offset); + } + } + + private static final class Context { + private Area area = Area.NONE; + private Token token; + private Type type; + private boolean headerModifier; + private String modifier; + } + + private static final class Scope { + private final Type base; + private Type current; + private String lastName; + + private Scope(final Type type) { + base = type; + current = type; + } + } + + /** + * @param text open document snapshot + * @param position caret position in UTF-16 units + * @param catalog document-scoped indexed types + * @param cancelled cancellation/stale-document predicate + * @return context-specific, token-replacing proposals; incomplete when the limit is reached + */ + public CompletionList complete(final String text, final Position position, final TypeCatalog catalog, + final BooleanSupplier cancelled) { + final CompletionList result = emptyCompletion(); + if (text.length() > ImpexCsvScanner.MAX_DOCUMENT_LENGTH || cancelled.getAsBoolean()) { + return result; + } + final TextPositions positions = new TextPositions(text); + final int offset; + final List records; + try { + offset = positions.offsetAt(position); + records = new ImpexCsvScanner().scan(text, cancelled); + } catch (final IllegalArgumentException e) { + return result; + } + final Context context = context(text, offset, records, catalog); + switch (context.area) { + case TYPE: + for (final Type type : catalog.getTypes()) { + if (cancelled.getAsBoolean()) { + return emptyCompletion(); + } + if (!offer(result, type.getCode(), type.getJavaClass(), CompletionItemKind.Class, context.token, positions)) { + break; + } + } + break; + case ATTRIBUTE: + if (context.type != null) { + for (final Attribute attribute : context.type.getAttributes()) { + if (!offer(result, attribute.getName(), attribute.getJavaType(), CompletionItemKind.Property, + context.token, positions)) { + break; + } + } + } + break; + case OPERATION: + words(result, OPERATIONS, Messages.operation, CompletionItemKind.Keyword, context.token, positions); + break; + case MODIFIER: + words(result, context.headerModifier ? HEADER_MODIFIERS : COLUMN_MODIFIERS, + context.headerModifier ? Messages.headerModifier : Messages.columnModifier, + CompletionItemKind.Property, context.token, positions); + break; + case VALUE: + if ("mode".equalsIgnoreCase(context.modifier)) { //$NON-NLS-1$ + words(result, Arrays.asList("append", "remove", "merge"), Messages.modifierValue, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + CompletionItemKind.Value, context.token, positions); + } else if (BOOLEAN_MODIFIERS.stream().anyMatch(name -> name.equalsIgnoreCase(context.modifier))) { + words(result, Arrays.asList("true", "false"), Messages.modifierValue, //$NON-NLS-1$ //$NON-NLS-2$ + CompletionItemKind.Value, context.token, positions); + } + break; + case MACRO: + final Set names = new TreeSet<>(); + for (final CsvRecord record : records) { + if (record.getEnd() <= offset && record.getContentEnd() < offset && record.getKind() == Kind.MACRO) { + final Matcher definition = MACRO.matcher(ImpexCsvScanner.valueOf(record.getCells().getFirst())); + if (definition.find()) { + names.add(definition.group(1)); + } + } + } + words(result, new ArrayList<>(names), Messages.macro, CompletionItemKind.Variable, context.token, positions); + break; + default: + break; + } + return cancelled.getAsBoolean() ? emptyCompletion() : result; + } + + /** + * @param text open document snapshot + * @param position requested UTF-16 position + * @param catalog document-scoped metadata + * @return indexed type/attribute declaration, or null when the context cannot be resolved safely + */ + public SourceTarget definition(final String text, final Position position, final TypeCatalog catalog) { + if (text.length() > ImpexCsvScanner.MAX_DOCUMENT_LENGTH) { + return null; + } + final Context context; + try { + context = context(text, new TextPositions(text).offsetAt(position), new ImpexCsvScanner().scan(text), catalog); + } catch (final IllegalArgumentException e) { + return null; + } + if (context.area == Area.TYPE) { + final Type type = catalog.getType(context.token.text); + return type == null ? null : new SourceTarget(type.getSourcePath(), type.getSourceLine()); + } + if (context.area == Area.ATTRIBUTE && context.type != null) { + final Attribute attribute = context.type.getAttribute(context.token.text); + return attribute == null ? null : new SourceTarget(attribute.getSourcePath(), attribute.getSourceLine()); + } + return null; + } + + /** @return an empty, complete proposal list */ + public static CompletionList emptyCompletion() { + return new CompletionList(false, new ArrayList<>()); + } + + private Context context(final String text, final int offset, final List records, + final TypeCatalog catalog) { + final Context result = new Context(); + result.token = new Token(text, offset, false); + CsvRecord record = null; + for (final CsvRecord candidate : records) { + if (candidate.getStart() <= offset && offset <= candidate.getContentEnd()) { + record = candidate; + break; + } + } + if (record != null && (record.getKind() == Kind.COMMENT || record.getKind() == Kind.SCRIPT)) { + return result; + } + if (result.token.text.startsWith("$")) { //$NON-NLS-1$ + result.area = Area.MACRO; + return result; + } + if (record == null) { + result.area = Area.OPERATION; + return result; + } + if (record.isMultiline() || record.getKind() == Kind.DATA || record.getKind() == Kind.MACRO) { + return result; + } + final String first = record.getCells().getFirst(); + final Matcher mode = MODE.matcher(first); + if (!mode.find()) { + if (first.trim().matches("[A-Za-z_]*")) { //$NON-NLS-1$ + result.area = Area.OPERATION; + } + return result; + } + if (offset <= record.getStart() + mode.end(1)) { + result.area = Area.OPERATION; + return result; + } + int typeEnd = mode.end(); + while (typeEnd < first.length() && nameChar(first.charAt(typeEnd), false)) { + typeEnd++; + } + final Type headerType = catalog.getType(first.substring(mode.end(), typeEnd)); + int cell = 0; + int cellStart = record.getStart(); + while (cell + 1 < record.getCells().size() + && offset > cellStart + record.getCells().get(cell).length()) { + cellStart += record.getCells().get(cell).length() + 1; + cell++; + } + if (cell == 0 && offset <= record.getStart() + typeEnd) { + result.area = Area.TYPE; + return result; + } + final String prefix = text.substring(cellStart, offset); + final int element = modifierElement(prefix); + if (element >= 0) { + result.token = new Token(text, offset, true); + final int equals = prefix.indexOf('=', element); + result.area = equals >= 0 ? Area.VALUE : Area.MODIFIER; + result.headerModifier = cell == 0; + result.modifier = equals >= 0 ? prefix.substring(element, equals).trim() : null; + return result; + } + if (cell > 0 && (prefix.indexOf('[') < 0 || prefix.lastIndexOf(']') >= prefix.lastIndexOf('['))) { + if (record.getCells().get(cell).trim().startsWith("@") //$NON-NLS-1$ + || record.getCells().get(cell).trim().startsWith("&")) { //$NON-NLS-1$ + return result; + } + result.area = Area.ATTRIBUTE; + result.type = referenceContext(catalog, headerType, text.substring(cellStart, result.token.start)); + } + return result; + } + + private int modifierElement(final String prefix) { + int element = -1; + char quote = 0; + for (int i = 0; i < prefix.length(); i++) { + final char c = prefix.charAt(i); + if (quote != 0) { + if (c == quote) { + quote = 0; + } + } else if (c == '\'' || c == '"') { + quote = c; + } else if (c == '[') { + element = i + 1; + } else if (c == ']') { + element = -1; + } else if (c == ',' && element >= 0) { + element = i + 1; + } + } + return quote == 0 ? element : -1; + } + + private Type referenceContext(final TypeCatalog catalog, final Type headerType, final String prefix) { + final Deque scopes = new ArrayDeque<>(); + scopes.push(new Scope(headerType)); + int brackets = 0; + char quote = 0; + for (int i = 0; i < prefix.length(); i++) { + final char c = prefix.charAt(i); + if (quote != 0) { + if (c == quote) { + quote = 0; + } + continue; + } + if (c == '\'' || c == '"') { + quote = c; + continue; + } + if (c == '[') { + brackets++; + } else if (c == ']') { + brackets--; + } else if (brackets == 0) { + final Scope scope = scopes.peek(); + if (c == '(') { + scopes.push(new Scope(reference(catalog, scope.current, scope.lastName))); + } else if (c == ')') { + if (scopes.size() == 1) { + return null; + } + scopes.pop(); + } else if (c == ',') { + scope.current = scope.base; + scope.lastName = null; + } else if (c == '.') { + final Attribute attribute = scope.current == null ? null : scope.current.getAttribute(scope.lastName); + scope.current = attribute != null ? catalog.referenceType(attribute.getJavaType()) + : catalog.getType(scope.lastName); + scope.lastName = null; + } else if (nameChar(c, false)) { + final int start = i; + while (i + 1 < prefix.length() && nameChar(prefix.charAt(i + 1), false)) { + i++; + } + scope.lastName = prefix.substring(start, i + 1); + } + } + } + return quote == 0 && brackets == 0 ? scopes.peek().current : null; + } + + private Type reference(final TypeCatalog catalog, final Type type, final String name) { + final Attribute attribute = type == null || name == null ? null : type.getAttribute(name); + return attribute == null ? null : catalog.referenceType(attribute.getJavaType()); + } + + private static boolean nameChar(final char c, final boolean dots) { + return Character.isLetterOrDigit(c) || c == '_' || c == '-' || c == '$' || (dots && c == '.'); + } + + private void words(final CompletionList result, final List words, final String detail, + final CompletionItemKind kind, final Token token, final TextPositions positions) { + for (final String word : new TreeSet<>(words)) { + if (!offer(result, word, detail, kind, token, positions)) { + break; + } + } + } + + private boolean offer(final CompletionList result, final String label, final String detail, + final CompletionItemKind kind, final Token token, final TextPositions positions) { + if (!label.regionMatches(true, 0, token.prefix, 0, token.prefix.length())) { + return true; + } + if (result.getItems().size() >= MAX_PROPOSALS) { + result.setIsIncomplete(true); + return false; + } + final CompletionItem item = new CompletionItem(label); + item.setDetail(detail); + item.setKind(kind); + item.setTextEdit(Either.forLeft(new TextEdit(new Range(positions.positionAt(token.start), + positions.positionAt(token.end)), label))); + result.getItems().add(item); + return true; + } +} diff --git a/com.hybris.hyeclipse.impex.ls/src/com/hybris/hyeclipse/impex/ls/types/Messages.java b/com.hybris.hyeclipse.impex.ls/src/com/hybris/hyeclipse/impex/ls/types/Messages.java new file mode 100644 index 00000000..18749948 --- /dev/null +++ b/com.hybris.hyeclipse.impex.ls/src/com/hybris/hyeclipse/impex/ls/types/Messages.java @@ -0,0 +1,27 @@ +/******************************************************************************* + * Copyright 2020 SAP + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + ******************************************************************************/ +package com.hybris.hyeclipse.impex.ls.types; + +import org.eclipse.osgi.util.NLS; + +final class Messages extends NLS { + public static String operation; + public static String macro; + public static String headerModifier; + public static String columnModifier; + public static String modifierValue; + + static { + NLS.initializeMessages("com.hybris.hyeclipse.impex.ls.types.Messages", Messages.class); //$NON-NLS-1$ + } + + private Messages() { + } +} diff --git a/com.hybris.hyeclipse.impex.ls/src/com/hybris/hyeclipse/impex/ls/types/Messages.properties b/com.hybris.hyeclipse.impex.ls/src/com/hybris/hyeclipse/impex/ls/types/Messages.properties new file mode 100644 index 00000000..2573c6f3 --- /dev/null +++ b/com.hybris.hyeclipse.impex.ls/src/com/hybris/hyeclipse/impex/ls/types/Messages.properties @@ -0,0 +1,5 @@ +operation=ImpEx operation +macro=ImpEx macro defined earlier in this document +headerModifier=ImpEx header modifier +columnModifier=ImpEx column modifier +modifierValue=ImpEx modifier value diff --git a/com.hybris.hyeclipse.impex.ls/src/com/hybris/hyeclipse/impex/ls/types/TypeCatalog.java b/com.hybris.hyeclipse.impex.ls/src/com/hybris/hyeclipse/impex/ls/types/TypeCatalog.java new file mode 100644 index 00000000..e79c08ab --- /dev/null +++ b/com.hybris.hyeclipse.impex.ls/src/com/hybris/hyeclipse/impex/ls/types/TypeCatalog.java @@ -0,0 +1,185 @@ +/******************************************************************************* + * Copyright 2020 SAP + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + ******************************************************************************/ +package com.hybris.hyeclipse.impex.ls.types; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Map; +import java.util.TreeMap; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** Immutable language metadata, independent of Eclipse workspace and UI classes. */ +public final class TypeCatalog { + + private static final Pattern JAVA_NAME = Pattern.compile("[\\w.$]+"); //$NON-NLS-1$ + private static final TypeCatalog EMPTY = new TypeCatalog(new ArrayList<>()); + private final Map types; + + /** Source metadata for an attribute, including inherited declarations. */ + public static final class Attribute { + private final String name; + private final String javaType; + private final String sourcePath; + private final int sourceLine; + + /** + * @param name qualifier + * @param javaType accessor Java type + * @param sourcePath provider-specific source identity + * @param sourceLine one-based declaration line + */ + public Attribute(final String name, final String javaType, final String sourcePath, final int sourceLine) { + this.name = name; + this.javaType = javaType; + this.sourcePath = sourcePath; + this.sourceLine = sourceLine; + } + + /** @return qualifier */ + public String getName() { return name; } + /** @return accessor Java type */ + public String getJavaType() { return javaType; } + /** @return provider-specific source identity */ + public String getSourcePath() { return sourcePath; } + /** @return one-based declaration line */ + public int getSourceLine() { return sourceLine; } + } + + /** Source-derived type and its effective attributes. */ + public static final class Type { + private final String code; + private final String javaClass; + private final String sourcePath; + private final int sourceLine; + private final Map attributes; + + /** + * @param code Commerce type code + * @param javaClass fully qualified generated model class + * @param sourcePath provider-specific source identity + * @param sourceLine one-based declaration line + * @param attributes effective attributes, including inherited ones + */ + public Type(final String code, final String javaClass, final String sourcePath, final int sourceLine, + final Collection attributes) { + this.code = code; + this.javaClass = javaClass; + this.sourcePath = sourcePath; + this.sourceLine = sourceLine; + final Map values = new TreeMap<>(); + for (final Attribute attribute : attributes) { + values.put(attribute.getName(), attribute); + } + this.attributes = Collections.unmodifiableMap(values); + } + + /** @return Commerce type code */ + public String getCode() { return code; } + /** @return generated model class */ + public String getJavaClass() { return javaClass; } + /** @return provider-specific source identity */ + public String getSourcePath() { return sourcePath; } + /** @return one-based declaration line */ + public int getSourceLine() { return sourceLine; } + /** @return immutable attributes sorted by qualifier */ + public Collection getAttributes() { return attributes.values(); } + + /** + * @param name qualifier + * @return exact or unambiguous case-insensitive match + */ + public Attribute getAttribute(final String name) { + if (name == null) { + return null; + } + if (attributes.containsKey(name)) { + return attributes.get(name); + } + Attribute found = null; + for (final Attribute attribute : attributes.values()) { + if (attribute.getName().equalsIgnoreCase(name)) { + if (found != null) { + return null; + } + found = attribute; + } + } + return found; + } + } + + /** @param types source-derived types */ + public TypeCatalog(final Collection types) { + final Map values = new TreeMap<>(); + for (final Type type : types) { + if (values.put(type.getCode(), type) != null) { + throw new IllegalArgumentException("Duplicate Commerce type code: " + type.getCode()); //$NON-NLS-1$ + } + } + this.types = Collections.unmodifiableMap(values); + } + + /** @return shared empty catalog */ + public static TypeCatalog empty() { return EMPTY; } + /** @return immutable types sorted by code */ + public Collection getTypes() { return types.values(); } + + /** + * @param code type code + * @return exact or unambiguous case-insensitive match + */ + public Type getType(final String code) { + if (code == null) { + return null; + } + if (types.containsKey(code)) { + return types.get(code); + } + Type found = null; + for (final Type type : types.values()) { + if (type.getCode().equalsIgnoreCase(code)) { + if (found != null) { + return null; + } + found = type; + } + } + return found; + } + + /** + * Resolves a reference/collection accessor to one indexed model type, never by guessing a type code. + * @param javaType accessor type, possibly including generic arguments + * @return unique indexed model, or null for unknown/ambiguous types + */ + public Type referenceType(final String javaType) { + if (javaType == null) { + return null; + } + Type found = null; + final Matcher names = JAVA_NAME.matcher(javaType); + while (names.find()) { + final String name = names.group(); + for (final Type type : types.values()) { + final String model = type.getJavaClass(); + if (model.equals(name) || (name.indexOf('.') < 0 + && model.substring(model.lastIndexOf('.') + 1).equals(name))) { + if (found != null && found != type) { + return null; + } + found = type; + } + } + } + return found; + } +} diff --git a/com.hybris.hyeclipse.impex.ls/src/com/hybris/hyeclipse/impex/ls/types/TypeSystemProvider.java b/com.hybris.hyeclipse.impex.ls/src/com/hybris/hyeclipse/impex/ls/types/TypeSystemProvider.java new file mode 100644 index 00000000..a7265ea3 --- /dev/null +++ b/com.hybris.hyeclipse.impex.ls/src/com/hybris/hyeclipse/impex/ls/types/TypeSystemProvider.java @@ -0,0 +1,34 @@ +/******************************************************************************* + * Copyright 2020 SAP + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + ******************************************************************************/ +package com.hybris.hyeclipse.impex.ls.types; + +import org.eclipse.lsp4j.Location; + +/** Host adapter boundary: the language server does not access the workspace or filesystem directly. */ +@FunctionalInterface +public interface TypeSystemProvider { + + /** + * @param documentUri open document identity + * @return immutable metadata belonging to this document, or an empty catalog; + * retain snapshot identity until metadata changes so in-flight results can be checked + */ + TypeCatalog getCatalog(String documentUri); + + /** + * @param documentUri requesting document identity + * @param sourcePath source identity from the catalog + * @param sourceLine one-based declaration line + * @return accessible source location, or null when unavailable/outside the document's platform + */ + default Location resolveLocation(final String documentUri, final String sourcePath, final int sourceLine) { + return null; + } +} diff --git a/com.hybris.hyeclipse.impex.tests/META-INF/MANIFEST.MF b/com.hybris.hyeclipse.impex.tests/META-INF/MANIFEST.MF index 18213cb6..a2bb7bca 100644 --- a/com.hybris.hyeclipse.impex.tests/META-INF/MANIFEST.MF +++ b/com.hybris.hyeclipse.impex.tests/META-INF/MANIFEST.MF @@ -16,6 +16,7 @@ Require-Bundle: org.junit, org.eclipse.lsp4j.jsonrpc, org.eclipse.lsp4e, com.hybris.hyeclipse.impex.ls, + com.hybris.hyeclipse.commons, com.hybris.hyeclipse.impex, com.hybris.hyeclipse.impexed Automatic-Module-Name: com.hybris.hyeclipse.impex.tests diff --git a/com.hybris.hyeclipse.impex.tests/src/com/hybris/hyeclipse/impex/tests/ImpexCompletionTest.java b/com.hybris.hyeclipse.impex.tests/src/com/hybris/hyeclipse/impex/tests/ImpexCompletionTest.java new file mode 100644 index 00000000..f99c44b4 --- /dev/null +++ b/com.hybris.hyeclipse.impex.tests/src/com/hybris/hyeclipse/impex/tests/ImpexCompletionTest.java @@ -0,0 +1,201 @@ +/******************************************************************************* + * Copyright 2020 SAP + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + ******************************************************************************/ +package com.hybris.hyeclipse.impex.tests; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import org.eclipse.lsp4j.CompletionItem; +import org.eclipse.lsp4j.CompletionList; +import org.eclipse.lsp4j.Position; +import org.eclipse.lsp4j.TextEdit; +import org.junit.Assert; +import org.junit.Test; + +import com.hybris.hyeclipse.impex.ls.format.TextPositions; +import com.hybris.hyeclipse.impex.ls.types.ImpexLanguageFeatures; +import com.hybris.hyeclipse.impex.ls.types.ImpexLanguageFeatures.SourceTarget; +import com.hybris.hyeclipse.impex.ls.types.TypeCatalog; +import com.hybris.hyeclipse.impex.ls.types.TypeCatalog.Attribute; +import com.hybris.hyeclipse.impex.ls.types.TypeCatalog.Type; + +public class ImpexCompletionTest { + + @Test + public void completesOperationsAndTypeNamesWithTokenReplacement() { + Assert.assertEquals(Arrays.asList("INSERT", "INSERT_UPDATE"), labels("INS|")); + final CompletionItem item = complete("INSERT_UPDATE Pro|duct;code").getItems().getFirst(); + Assert.assertEquals("Product", item.getLabel()); + Assert.assertEquals("demo.ProductModel", item.getDetail()); + final TextEdit edit = item.getTextEdit().getLeft(); + Assert.assertEquals(new Position(0, 14), edit.getRange().getStart()); + Assert.assertEquals(new Position(0, 21), edit.getRange().getEnd()); + Assert.assertEquals("Product", edit.getNewText()); + Assert.assertEquals(Arrays.asList("Catalog", "CatalogVersion", "Category", "Product"), labels("INSERT |")); + } + + @Test + public void completesAttributesIncludingInheritedQualifiers() { + Assert.assertEquals(Arrays.asList("name"), labels("INSERT Product;na|me[lang=en]")); + Assert.assertEquals(Arrays.asList("uid"), labels("INSERT Product;u|")); + Assert.assertEquals(Arrays.asList("catalogVersion"), labels("INSERT Product;CAT|")); + final CompletionItem item = complete("INSERT Product;na|me").getItems().getFirst(); + Assert.assertEquals(new Position(0, 15), item.getTextEdit().getLeft().getRange().getStart()); + Assert.assertEquals(new Position(0, 19), item.getTextEdit().getLeft().getRange().getEnd()); + } + + @Test + public void followsNestedReferencesCollectionsAndExplicitTypePaths() { + Assert.assertEquals(Arrays.asList("id"), labels("INSERT Product;catalogVersion(catalog(i|d),version)")); + Assert.assertEquals(Arrays.asList("version"), labels("INSERT Product;catalogVersion(catalog(id),v|ersion)")); + Assert.assertEquals(Arrays.asList("code"), labels("INSERT Product;supercategories(c|ode)")); + Assert.assertEquals(Arrays.asList("version"), labels("INSERT Product;catalogVersion(CatalogVersion.v|ersion)")); + Assert.assertEquals(Arrays.asList("id"), labels("INSERT Product;catalogVersion(catalog.i|d,version)")); + } + + @Test + public void modifiersStayInHeaderOrColumnContext() { + Assert.assertEquals(Arrays.asList("parallel"), labels("INSERT Product[pa|")); + Assert.assertEquals(Arrays.asList("path-delimiter"), labels("INSERT Product;code[pa|")); + Assert.assertEquals(Arrays.asList("disable.interceptor.beans", "disable.interceptor.types"), + labels("INSERT Product[disable.interce|")); + Assert.assertEquals(Arrays.asList("unique"), labels("INSERT Unknown;code[un|")); + Assert.assertEquals(Arrays.asList("unique"), labels("INSERT Product;code[default='a,b',un|")); + } + + @Test + public void completesOnlySupportedModifierValues() { + Assert.assertEquals(Arrays.asList("true"), labels("INSERT Product;code[unique=tr|")); + Assert.assertEquals(Arrays.asList("append", "merge", "remove"), labels("INSERT Product;groups[mode=|")); + Assert.assertTrue(labels("INSERT Product;creationtime[dateformat=|" ).isEmpty()); + Assert.assertTrue(labels("INSERT Product;code[default='tr|" ).isEmpty()); + } + + @Test + public void macrosAreDocumentLocalAndDefinedBeforeTheReference() { + Assert.assertEquals(Arrays.asList("$catalog"), labels("$catalog=one\n$catalog=two\n" + + "INSERT Product;code\n;id;$ca|\n$country=later\n")); + Assert.assertTrue(labels("INSERT Product;code\n;id;$ca|\n$catalog=later\n").isEmpty()); + Assert.assertTrue(labels("$catalog=$ca|").isEmpty()); + Assert.assertEquals(Arrays.asList("$catalog"), labels("$catalog=one\nINSERT Product;code[default=$ca|]")); + } + + @Test + public void doesNotGuessTypesInDataCommentsScriptsOrUnknownReferences() { + for (final String source : new String[] {"INSERT Product;code\n;na|", "# $ca|", "\"# $ca|\"", + "#% $ca|", "INSERT Unknown;na|", "INSERT Product;missing(na|)", + "INSERT Product;@me|", "INSERT Product;&doc|", "INSERT Product;\"na|\"", + "INSERT Product;code\\\nna|"}) { + Assert.assertTrue(source, labels(source).isEmpty()); + } + } + + @Test + public void definitionsUseIndexedDeclarationLocations() { + final SourceTarget type = definition("INSERT Pro|duct;code"); + Assert.assertEquals("/platform/ProductModel.java", type.getPath()); + Assert.assertEquals(10, type.getLine()); + final SourceTarget inherited = definition("INSERT Product;u|id"); + Assert.assertEquals("/platform/ItemModel.java", inherited.getPath()); + Assert.assertEquals(8, inherited.getLine()); + final SourceTarget nested = definition("INSERT Product;catalogVersion(catalog(i|d),version)"); + Assert.assertEquals("/platform/CatalogModel.java", nested.getPath()); + Assert.assertEquals(21, nested.getLine()); + Assert.assertNull(definition("INSERT Product;code\n;u|id")); + Assert.assertNull(definition("INSERT Product;code[un|ique=true]")); + } + + @Test + public void missingIndexStillOffersOperationsModifiersAndMacros() { + final ImpexLanguageFeatures features = new ImpexLanguageFeatures(); + Assert.assertFalse(features.complete("INS", new Position(0, 3), TypeCatalog.empty(), () -> false) + .getItems().isEmpty()); + Assert.assertTrue(features.complete("INSERT Product;", new Position(0, 15), TypeCatalog.empty(), () -> false) + .getItems().isEmpty()); + Assert.assertFalse(features.complete("INSERT Unknown;code[un", new Position(0, 22), TypeCatalog.empty(), + () -> false).getItems().isEmpty()); + } + + @Test + public void rejectsAmbiguousModelNamesRatherThanRemovingModelSuffixes() { + final List types = new ArrayList<>(catalog().getTypes()); + types.add(new Type("OtherCategory", "other.CategoryModel", "/platform/Other.java", 1, new ArrayList<>())); + final TypeCatalog ambiguous = new TypeCatalog(types); + Assert.assertNull(ambiguous.referenceType("CategoryModel")); + Assert.assertEquals("Category", ambiguous.referenceType("java.util.Collection").getCode()); + Assert.assertNull(ambiguous.referenceType("java.util.Map")); + Assert.assertNull(ambiguous.referenceType("UnknownModel")); + } + + @Test + public void boundsProposalsAndSupportsPrefixRefinement() { + final List types = new ArrayList<>(); + for (int i = 0; i < 300; i++) { + types.add(new Type(String.format("Type%03d", i), "demo.Model" + i, "/platform/Model.java", 1, + new ArrayList<>())); + } + final ImpexLanguageFeatures features = new ImpexLanguageFeatures(); + final TypeCatalog catalog = new TypeCatalog(types); + final CompletionList all = features.complete("INSERT ", new Position(0, 7), catalog, () -> false); + Assert.assertEquals(200, all.getItems().size()); + Assert.assertTrue(all.isIncomplete()); + final CompletionList refined = features.complete("INSERT Type29", new Position(0, 13), catalog, () -> false); + Assert.assertEquals(10, refined.getItems().size()); + Assert.assertFalse(refined.isIncomplete()); + } + + @Test + public void handlesCancellationInvalidPositionsAndUtf16ReplacementRanges() { + final ImpexLanguageFeatures features = new ImpexLanguageFeatures(); + Assert.assertTrue(features.complete("INSERT Product;", new Position(0, 15), catalog(), () -> true) + .getItems().isEmpty()); + Assert.assertTrue(features.complete("INSERT Product;", new Position(5, 0), catalog(), () -> false) + .getItems().isEmpty()); + final CompletionItem item = complete("# é😀\r\nINSERT Product;na|me").getItems().getFirst(); + Assert.assertEquals(new Position(1, 15), item.getTextEdit().getLeft().getRange().getStart()); + Assert.assertEquals(new Position(1, 19), item.getTextEdit().getLeft().getRange().getEnd()); + } + + private CompletionList complete(final String marked) { + final int offset = marked.indexOf('|'); + final String text = marked.replace("|", ""); + return new ImpexLanguageFeatures().complete(text, new TextPositions(text).positionAt(offset), catalog(), () -> false); + } + + private List labels(final String marked) { + return complete(marked).getItems().stream().map(CompletionItem::getLabel).collect(Collectors.toList()); + } + + private SourceTarget definition(final String marked) { + final int offset = marked.indexOf('|'); + final String text = marked.replace("|", ""); + return new ImpexLanguageFeatures().definition(text, new TextPositions(text).positionAt(offset), catalog()); + } + + static TypeCatalog catalog() { + return new TypeCatalog(Arrays.asList( + new Type("Product", "demo.ProductModel", "/platform/ProductModel.java", 10, Arrays.asList( + new Attribute("code", "java.lang.String", "/platform/ProductModel.java", 16), + new Attribute("name", "java.lang.String", "/platform/ProductModel.java", 18), + new Attribute("uid", "java.lang.String", "/platform/ItemModel.java", 8), + new Attribute("catalogVersion", "demo.CatalogVersionModel", "/platform/ProductModel.java", 20), + new Attribute("supercategories", "java.util.Collection", + "/platform/ProductModel.java", 24))), + new Type("CatalogVersion", "demo.CatalogVersionModel", "/platform/CatalogVersionModel.java", 10, + Arrays.asList(new Attribute("catalog", "demo.CatalogModel", "/platform/CatalogVersionModel.java", 21), + new Attribute("version", "java.lang.String", "/platform/CatalogVersionModel.java", 23))), + new Type("Catalog", "demo.CatalogModel", "/platform/CatalogModel.java", 10, + Arrays.asList(new Attribute("id", "java.lang.String", "/platform/CatalogModel.java", 21))), + new Type("Category", "demo.CategoryModel", "/platform/CategoryModel.java", 10, + Arrays.asList(new Attribute("code", "java.lang.String", "/platform/CategoryModel.java", 21))))); + } +} diff --git a/com.hybris.hyeclipse.impex.tests/src/com/hybris/hyeclipse/impex/tests/ImpexLanguageServerTest.java b/com.hybris.hyeclipse.impex.tests/src/com/hybris/hyeclipse/impex/tests/ImpexLanguageServerTest.java index f592fe36..6369115e 100644 --- a/com.hybris.hyeclipse.impex.tests/src/com/hybris/hyeclipse/impex/tests/ImpexLanguageServerTest.java +++ b/com.hybris.hyeclipse.impex.tests/src/com/hybris/hyeclipse/impex/tests/ImpexLanguageServerTest.java @@ -21,6 +21,8 @@ import org.eclipse.jface.text.Document; import org.eclipse.lsp4e.VersionedEdits; +import org.eclipse.lsp4j.CompletionParams; +import org.eclipse.lsp4j.DefinitionParams; import org.eclipse.lsp4j.DidChangeTextDocumentParams; import org.eclipse.lsp4j.DidCloseTextDocumentParams; import org.eclipse.lsp4j.DidOpenTextDocumentParams; @@ -104,7 +106,8 @@ public void advertisesOnlyImplementedServices() throws Exception { Assert.assertEquals("utf-16", capabilities.getPositionEncoding()); Assert.assertTrue(capabilities.getDocumentFormattingProvider().getLeft()); Assert.assertTrue(capabilities.getDocumentRangeFormattingProvider().getLeft()); - Assert.assertNull(capabilities.getCompletionProvider()); + Assert.assertNotNull(capabilities.getCompletionProvider()); + Assert.assertTrue(capabilities.getDefinitionProvider().getLeft()); Assert.assertNull(capabilities.getHoverProvider()); Assert.assertNull(capabilities.getDocumentSymbolProvider()); } @@ -195,6 +198,11 @@ public void exchangesRealJsonRpcMessagesAndCanRestartConnection() throws Excepti final List edits = remote.getTextDocumentService().formatting(formatting()) .get(5, TimeUnit.SECONDS); Assert.assertEquals(2, edits.size()); + Assert.assertEquals(4, remote.getTextDocumentService().completion(new CompletionParams( + new TextDocumentIdentifier(URI), new Position(0, 0))).get(5, TimeUnit.SECONDS) + .getRight().getItems().size()); + Assert.assertTrue(remote.getTextDocumentService().definition(new DefinitionParams( + new TextDocumentIdentifier(URI), new Position(0, 1))).get(5, TimeUnit.SECONDS).getLeft().isEmpty()); remote.shutdown().get(5, TimeUnit.SECONDS); remote.exit(); } finally { diff --git a/com.hybris.hyeclipse.impex.tests/src/com/hybris/hyeclipse/impex/tests/ImpexTypeServiceTest.java b/com.hybris.hyeclipse.impex.tests/src/com/hybris/hyeclipse/impex/tests/ImpexTypeServiceTest.java new file mode 100644 index 00000000..a698d2dc --- /dev/null +++ b/com.hybris.hyeclipse.impex.tests/src/com/hybris/hyeclipse/impex/tests/ImpexTypeServiceTest.java @@ -0,0 +1,156 @@ +/******************************************************************************* + * Copyright 2020 SAP + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + ******************************************************************************/ +package com.hybris.hyeclipse.impex.tests; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import java.util.stream.Collectors; + +import org.eclipse.lsp4j.CompletionItem; +import org.eclipse.lsp4j.CompletionList; +import org.eclipse.lsp4j.CompletionParams; +import org.eclipse.lsp4j.DidChangeTextDocumentParams; +import org.eclipse.lsp4j.DidOpenTextDocumentParams; +import org.eclipse.lsp4j.Position; +import org.eclipse.lsp4j.TextDocumentContentChangeEvent; +import org.eclipse.lsp4j.TextDocumentIdentifier; +import org.eclipse.lsp4j.TextDocumentItem; +import org.eclipse.lsp4j.VersionedTextDocumentIdentifier; +import org.eclipse.lsp4j.jsonrpc.messages.Either; +import org.junit.Assert; +import org.junit.Test; + +import com.hybris.hyeclipse.impex.ls.ImpexLanguageServer; +import com.hybris.hyeclipse.impex.ls.types.TypeCatalog; +import com.hybris.hyeclipse.impex.ls.types.TypeSystemProvider; + +public class ImpexTypeServiceTest { + + private static final String URI = "file:///A/sample.impex"; + private static final String OTHER_URI = "file:///B/sample.impex"; + private static final String SOURCE = "INSERT Product;"; + + @Test + public void neverSharesTypesBetweenDocumentCatalogs() throws Exception { + final Map catalogs = new HashMap<>(); + catalogs.put(URI, catalog("alpha")); + catalogs.put(OTHER_URI, catalog("beta")); + try (final ImpexLanguageServer server = new ImpexLanguageServer( + uri -> catalogs.getOrDefault(uri, TypeCatalog.empty()))) { + open(server, URI); + open(server, OTHER_URI); + Assert.assertEquals(Arrays.asList("alpha"), labels(server, URI)); + Assert.assertEquals(Arrays.asList("beta"), labels(server, OTHER_URI)); + } + } + + @Test + public void adoptsUpdatedSharedMetadataWithoutReopeningTheDocument() throws Exception { + final AtomicReference snapshot = new AtomicReference<>(catalog("code")); + try (final ImpexLanguageServer server = new ImpexLanguageServer(uri -> snapshot.get())) { + open(server, URI); + Assert.assertEquals(Arrays.asList("code"), labels(server, URI)); + snapshot.set(catalog("updated")); + Assert.assertEquals(Arrays.asList("updated"), labels(server, URI)); + } + } + + @Test + public void discardsCompletionsIfTheIndexChangesDuringTheRequest() throws Exception { + final AtomicInteger lookups = new AtomicInteger(); + final TypeCatalog original = catalog("original"); + final TypeCatalog updated = catalog("updated"); + try (final ImpexLanguageServer server = new ImpexLanguageServer( + uri -> lookups.getAndIncrement() == 0 ? original : updated)) { + open(server, URI); + Assert.assertTrue(labels(server, URI).isEmpty()); + Assert.assertEquals(Arrays.asList("updated"), labels(server, URI)); + } + } + + @Test + public void discardsCompletionsIfTheDocumentChangesDuringMetadataLookup() throws Exception { + final CountDownLatch entered = new CountDownLatch(1); + final CountDownLatch release = new CountDownLatch(1); + final AtomicBoolean first = new AtomicBoolean(true); + final TypeCatalog catalog = catalog("code"); + final TypeSystemProvider provider = uri -> { + if (first.getAndSet(false)) { + entered.countDown(); + try { + Assert.assertTrue(release.await(5, TimeUnit.SECONDS)); + } catch (final InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + return catalog; + }; + try (final ImpexLanguageServer server = new ImpexLanguageServer(provider)) { + open(server, URI); + final CompletableFuture, CompletionList>> request = server.completion(params(URI)); + Assert.assertTrue(entered.await(5, TimeUnit.SECONDS)); + server.didChange(new DidChangeTextDocumentParams(new VersionedTextDocumentIdentifier(URI, 2), + Arrays.asList(new TextDocumentContentChangeEvent("# changed\n")))); + release.countDown(); + Assert.assertTrue(request.get(5, TimeUnit.SECONDS).getRight().getItems().isEmpty()); + } finally { + release.countDown(); + } + } + + @Test + public void shutdownCancelsPendingCompletionRequests() throws Exception { + final CountDownLatch entered = new CountDownLatch(1); + final CountDownLatch release = new CountDownLatch(1); + try (final ImpexLanguageServer server = new ImpexLanguageServer(uri -> { + entered.countDown(); + try { + release.await(5, TimeUnit.SECONDS); + } catch (final InterruptedException e) { + Thread.currentThread().interrupt(); + } + return TypeCatalog.empty(); + })) { + open(server, URI); + final CompletableFuture, CompletionList>> request = server.completion(params(URI)); + Assert.assertTrue(entered.await(5, TimeUnit.SECONDS)); + server.close(); + Assert.assertTrue(request.isCancelled()); + } finally { + release.countDown(); + } + } + + private TypeCatalog catalog(final String attribute) { + return new TypeCatalog(Arrays.asList(new TypeCatalog.Type("Product", "demo.ProductModel", "/platform/Product.java", + 1, Arrays.asList(new TypeCatalog.Attribute(attribute, "java.lang.String", "/platform/Product.java", 2))))); + } + + private void open(final ImpexLanguageServer server, final String uri) { + server.didOpen(new DidOpenTextDocumentParams(new TextDocumentItem(uri, "impex", 1, SOURCE))); + } + + private CompletionParams params(final String uri) { + return new CompletionParams(new TextDocumentIdentifier(uri), new Position(0, SOURCE.length())); + } + + private List labels(final ImpexLanguageServer server, final String uri) throws Exception { + return server.completion(params(uri)).get(5, TimeUnit.SECONDS).getRight().getItems().stream() + .map(CompletionItem::getLabel).collect(Collectors.toList()); + } +} diff --git a/com.hybris.hyeclipse.impex.tests/src/com/hybris/hyeclipse/impex/tests/WorkspaceTypeSystemProviderTest.java b/com.hybris.hyeclipse.impex.tests/src/com/hybris/hyeclipse/impex/tests/WorkspaceTypeSystemProviderTest.java new file mode 100644 index 00000000..5309837a --- /dev/null +++ b/com.hybris.hyeclipse.impex.tests/src/com/hybris/hyeclipse/impex/tests/WorkspaceTypeSystemProviderTest.java @@ -0,0 +1,188 @@ +/******************************************************************************* + * Copyright 2020 SAP + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + ******************************************************************************/ +package com.hybris.hyeclipse.impex.tests; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; + +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.IProjectDescription; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.IWorkspace; +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.lsp4j.CompletionParams; +import org.eclipse.lsp4j.DefinitionParams; +import org.eclipse.lsp4j.DidOpenTextDocumentParams; +import org.eclipse.lsp4j.Location; +import org.eclipse.lsp4j.Position; +import org.eclipse.lsp4j.TextDocumentIdentifier; +import org.eclipse.lsp4j.TextDocumentItem; +import org.junit.After; +import org.junit.Assert; +import org.junit.Assume; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import com.hybris.hyeclipse.commons.Constants; +import com.hybris.hyeclipse.commons.typesystem.TypeSystemSnapshot; +import com.hybris.hyeclipse.commons.typesystem.YAttributeDescriptor; +import com.hybris.hyeclipse.commons.typesystem.YType; +import com.hybris.hyeclipse.impex.ls.ImpexLanguageServer; +import com.hybris.hyeclipse.impex.ls.types.TypeCatalog; +import com.hybris.hyeclipse.impex.lsp.WorkspaceTypeSystemProvider; + +public class WorkspaceTypeSystemProviderTest { + + @Rule + public final TemporaryFolder temporary = new TemporaryFolder(); + private final IWorkspace workspace = ResourcesPlugin.getWorkspace(); + private final List created = new ArrayList<>(); + private final AtomicReference snapshot = new AtomicReference<>(); + private IProject platform; + private IFile document; + private IFile otherDocument; + private IFile model; + private WorkspaceTypeSystemProvider provider; + + @Before + public void setUp() throws Exception { + Assume.assumeFalse(workspace.getRoot().getProject(Constants.PLATFROM).exists()); + platform = project(Constants.PLATFROM, temporary.newFolder("A", "hybris", "bin", "platform")); + final IProject extension = project("impex-extension-" + UUID.randomUUID(), + temporary.newFolder("A", "hybris", "bin", "custom", "store space")); + final IProject other = project("impex-other-" + UUID.randomUUID(), + temporary.newFolder("B", "hybris", "bin", "custom", "other")); + document = file(extension, "sample.impex", "INSERT Product;code"); + otherDocument = file(other, "sample.impex", "INSERT Product;code"); + model = file(platform, "ProductModel.java", "\n".repeat(20)); + snapshot.set(snapshot("code")); + provider = new WorkspaceTypeSystemProvider(workspace, snapshot::get); + } + + @After + public void tearDown() throws Exception { + for (int i = created.size() - 1; i >= 0; i--) { + created.get(i).delete(true, true, null); + } + } + + @Test + public void catalogIsScopedToTheIndexedCommerceTree() { + Assert.assertEquals("Product", provider.getCatalog(uri(document)).getTypes().iterator().next().getCode()); + Assert.assertTrue(provider.getCatalog(uri(otherDocument)).getTypes().isEmpty()); + Assert.assertTrue(provider.getCatalog("file:///unopened/sample.impex").getTypes().isEmpty()); + Assert.assertTrue(provider.getCatalog("https://example.invalid/sample.impex").getTypes().isEmpty()); + Assert.assertTrue(provider.getCatalog("not a valid URI").getTypes().isEmpty()); + Assert.assertTrue(provider.getCatalog("file:relative").getTypes().isEmpty()); + Assert.assertTrue(provider.getCatalog(null).getTypes().isEmpty()); + } + + @Test + public void refreshesTheCatalogOnlyWhenTheSharedSnapshotChanges() { + final TypeCatalog first = provider.getCatalog(uri(document)); + Assert.assertSame(first, provider.getCatalog(uri(document))); + snapshot.set(snapshot("updated")); + final TypeCatalog updated = provider.getCatalog(uri(document)); + Assert.assertNotSame(first, updated); + Assert.assertNotNull(updated.getType("Product").getAttribute("updated")); + Assert.assertNull(updated.getType("Product").getAttribute("code")); + Assert.assertNotNull(first.getType("Product").getAttribute("code")); + } + + @Test + public void emptySnapshotsHaveStableIdentityForSyntaxOnlyAssistance() { + final WorkspaceTypeSystemProvider empty = new WorkspaceTypeSystemProvider(workspace, TypeSystemSnapshot::empty); + Assert.assertSame(TypeCatalog.empty(), empty.getCatalog(uri(document))); + Assert.assertSame(TypeCatalog.empty(), empty.getCatalog(uri(document))); + } + + @Test + public void closedPlatformAndAmbiguousWorkspaceAliasesDoNotLeakTypes() throws Exception { + platform.close(null); + Assert.assertTrue(provider.getCatalog(uri(document)).getTypes().isEmpty()); + platform.open(null); + final IFile alias = otherDocument.getProject().getFile("alias.impex"); + alias.createLink(document.getLocationURI(), IResource.NONE, null); + Assert.assertTrue(provider.getCatalog(uri(document)).getTypes().isEmpty()); + alias.delete(true, null); + Assert.assertFalse(provider.getCatalog(uri(document)).getTypes().isEmpty()); + } + + @Test + public void resolvesOnlyAccessibleSourceLocationsInTheSameTree() throws Exception { + final Location location = provider.resolveLocation(uri(document), model.getFullPath().toPortableString(), 11); + Assert.assertEquals(uri(model), location.getUri()); + Assert.assertEquals(new Position(10, 0), location.getRange().getStart()); + Assert.assertNull(provider.resolveLocation(uri(otherDocument), model.getFullPath().toPortableString(), 11)); + Assert.assertNull(provider.resolveLocation(uri(document), otherDocument.getFullPath().toPortableString(), 11)); + Assert.assertNull(provider.resolveLocation(uri(document), "relative.java", 1)); + Assert.assertNull(provider.resolveLocation(uri(document), model.getFullPath().toPortableString(), 0)); + model.delete(true, null); + Assert.assertNull(provider.resolveLocation(uri(document), model.getFullPath().toPortableString(), 11)); + } + + @Test + public void serverUsesWorkspaceMetadataWithoutImportingOrExecutingCommerce() throws Exception { + try (final ImpexLanguageServer server = new ImpexLanguageServer(provider)) { + final String text = "INSERT Product;code"; + server.didOpen(new DidOpenTextDocumentParams(new TextDocumentItem(uri(document), "impex", 1, text))); + Assert.assertEquals("code", server.completion(new CompletionParams(new TextDocumentIdentifier(uri(document)), + new Position(0, 17))).get(5, TimeUnit.SECONDS).getRight().getItems().getFirst().getLabel()); + final Location target = server.definition(new DefinitionParams(new TextDocumentIdentifier(uri(document)), + new Position(0, 16))).get(5, TimeUnit.SECONDS).getLeft().getFirst(); + Assert.assertEquals(uri(model), target.getUri()); + Assert.assertEquals(new Position(10, 0), target.getRange().getStart()); + server.didOpen(new DidOpenTextDocumentParams(new TextDocumentItem(uri(otherDocument), "impex", 1, text))); + Assert.assertTrue(server.completion(new CompletionParams(new TextDocumentIdentifier(uri(otherDocument)), + new Position(0, 17))).get(5, TimeUnit.SECONDS).getRight().getItems().isEmpty()); + Assert.assertTrue(server.definition(new DefinitionParams(new TextDocumentIdentifier(uri(otherDocument)), + new Position(0, 16))).get(5, TimeUnit.SECONDS).getLeft().isEmpty()); + } + } + + private TypeSystemSnapshot snapshot(final String attribute) { + return new TypeSystemSnapshot(Arrays.asList(new YType("Product", "demo.ProductModel", "demo.ItemModel", + model.getFullPath().toPortableString(), 10, Arrays.asList(new YAttributeDescriptor(attribute, + "java.lang.String", "demo.ProductModel", model.getFullPath().toPortableString(), 11))))); + } + + private IProject project(final String name, final File location) throws Exception { + final IProject project = workspace.getRoot().getProject(name); + final IProjectDescription description = workspace.newProjectDescription(name); + description.setLocationURI(location.toURI()); + project.create(description, new NullProgressMonitor()); + created.add(project); + project.open(null); + return project; + } + + private IFile file(final IProject project, final String name, final String contents) throws Exception { + final IFile file = project.getFile(name); + try (final ByteArrayInputStream input = new ByteArrayInputStream(contents.getBytes(StandardCharsets.UTF_8))) { + file.create(input, false, null); + } + return file; + } + + private String uri(final IFile file) { + return file.getLocationURI().toString(); + } +} diff --git a/com.hybris.hyeclipse.impex/META-INF/MANIFEST.MF b/com.hybris.hyeclipse.impex/META-INF/MANIFEST.MF index d5a61058..10eddcf3 100644 --- a/com.hybris.hyeclipse.impex/META-INF/MANIFEST.MF +++ b/com.hybris.hyeclipse.impex/META-INF/MANIFEST.MF @@ -19,6 +19,7 @@ Require-Bundle: org.eclipse.core.contenttype, org.eclipse.lsp4e, org.eclipse.lsp4j, org.eclipse.lsp4j.jsonrpc, + com.hybris.hyeclipse.commons, com.hybris.hyeclipse.impex.ls Automatic-Module-Name: com.hybris.hyeclipse.impex Export-Package: com.hybris.hyeclipse.impex.wizards, diff --git a/com.hybris.hyeclipse.impex/README.md b/com.hybris.hyeclipse.impex/README.md index b4acf2de..03529093 100644 --- a/com.hybris.hyeclipse.impex/README.md +++ b/com.hybris.hyeclipse.impex/README.md @@ -27,8 +27,20 @@ continued, malformed, or unsupported blocks are left unchanged. See the [formatting policy](../com.hybris.hyeclipse.impex.ls/README.md) for limits and options. The legacy formatter shortcut is scoped to its own editor to avoid interference. -Type-system completion/navigation, macro assistance, symbols, and diagnostics are -not implemented yet. Use the legacy editor for type-system completion workflows. +Content assist (**Ctrl+Space**) now offers operation/type names, inherited +attributes, nested reference attributes, header/column modifiers, supported modifier +values, and macros defined earlier in the document. Definition hyperlinks resolve +indexed type/attribute declarations to their generated Java sources. + +Indexed proposals are limited to workspace files in the Commerce tree belonging to +the open project named `platform`. Other/unindexed roots, external extensions, and +ambiguous workspace aliases get syntax/macro assistance only—not another platform's +types. The index is reused and refreshed by the existing background indexing jobs. +Quoted/continued headers and macro-expanded header structures are not yet resolved +for type assistance. See the [language-service policy](../com.hybris.hyeclipse.impex.ls/README.md). + +Macro hover, symbols, diagnostics, and interactive UI/upgrade validation remain +subsequent slices. The legacy editor has not been retired. Run the isolated OSGi tests: @@ -38,6 +50,7 @@ Run the isolated OSGi tests: Rebuild both editor bundles so registration tests do not use cached legacy metadata. The tests exercise the packaged grammar, file creation, registration, formatting, -real JSON-RPC lifecycle, and LSP4E's stale-edit protection and document undo/redo. +real JSON-RPC lifecycle, scoped completion/navigation, index refresh, cancellation, +and LSP4E's stale-edit protection and document undo/redo. They do not replace interactive shortcut, wizard, light/dark-theme, and existing-workspace upgrade testing. diff --git a/com.hybris.hyeclipse.impex/src/com/hybris/hyeclipse/impex/lsp/ImpexConnectionProvider.java b/com.hybris.hyeclipse.impex/src/com/hybris/hyeclipse/impex/lsp/ImpexConnectionProvider.java index a765e303..933fe7de 100644 --- a/com.hybris.hyeclipse.impex/src/com/hybris/hyeclipse/impex/lsp/ImpexConnectionProvider.java +++ b/com.hybris.hyeclipse.impex/src/com/hybris/hyeclipse/impex/lsp/ImpexConnectionProvider.java @@ -48,7 +48,7 @@ public synchronized void start() throws IOException { serverOutput = new PipedOutputStream(input); serverInput = new PipedInputStream(PIPE_BUFFER_SIZE); output = new PipedOutputStream(serverInput); - server = new ImpexLanguageServer(); + server = new ImpexLanguageServer(new WorkspaceTypeSystemProvider()); transport = Executors.newFixedThreadPool(2, runnable -> { final Thread thread = new Thread(runnable, "ImpEx LSP transport"); //$NON-NLS-1$ thread.setDaemon(true); diff --git a/com.hybris.hyeclipse.impex/src/com/hybris/hyeclipse/impex/lsp/WorkspaceTypeSystemProvider.java b/com.hybris.hyeclipse.impex/src/com/hybris/hyeclipse/impex/lsp/WorkspaceTypeSystemProvider.java new file mode 100644 index 00000000..412b4543 --- /dev/null +++ b/com.hybris.hyeclipse.impex/src/com/hybris/hyeclipse/impex/lsp/WorkspaceTypeSystemProvider.java @@ -0,0 +1,140 @@ +/******************************************************************************* + * Copyright 2020 SAP + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + ******************************************************************************/ +package com.hybris.hyeclipse.impex.lsp; + +import java.net.URI; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.function.Supplier; + +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.IWorkspace; +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.core.runtime.IPath; +import org.eclipse.lsp4j.Location; +import org.eclipse.lsp4j.Position; +import org.eclipse.lsp4j.Range; + +import com.hybris.hyeclipse.commons.Activator; +import com.hybris.hyeclipse.commons.Constants; +import com.hybris.hyeclipse.commons.typesystem.TypeSystemSnapshot; +import com.hybris.hyeclipse.commons.typesystem.YAttributeDescriptor; +import com.hybris.hyeclipse.commons.typesystem.YType; +import com.hybris.hyeclipse.impex.ls.types.TypeCatalog; +import com.hybris.hyeclipse.impex.ls.types.TypeSystemProvider; + +/** Maps documents to the single currently indexed platform without global fallback or source parsing. */ +public final class WorkspaceTypeSystemProvider implements TypeSystemProvider { + + private final IWorkspace workspace; + private final Supplier snapshots; + private TypeSystemSnapshot previous; + private TypeCatalog cached = TypeCatalog.empty(); + + /** Uses the shared, non-blocking generated-model index. */ + public WorkspaceTypeSystemProvider() { + this(ResourcesPlugin.getWorkspace(), () -> Activator.getDefault() == null ? TypeSystemSnapshot.empty() + : Activator.getDefault().getTypeSystemIndex().getSnapshot()); + } + + /** + * @param workspace owning workspace + * @param snapshots non-blocking supplier of the indexed platform's latest snapshot + */ + public WorkspaceTypeSystemProvider(final IWorkspace workspace, final Supplier snapshots) { + this.workspace = workspace; + this.snapshots = snapshots; + } + + @Override + public synchronized TypeCatalog getCatalog(final String documentUri) { + if (documentRoot(documentUri) == null) { + return TypeCatalog.empty(); + } + final TypeSystemSnapshot snapshot = snapshots.get(); + if (snapshot == null || snapshot.getTypes().isEmpty()) { + return TypeCatalog.empty(); + } + if (snapshot != previous) { + final List types = new ArrayList<>(); + for (final YType type : snapshot.getTypes()) { + final List attributes = new ArrayList<>(); + for (final YAttributeDescriptor attribute : type.getAttributes()) { + attributes.add(new TypeCatalog.Attribute(attribute.getQualifier(), attribute.getJavaType(), + attribute.getSourcePath(), attribute.getSourceLine())); + } + types.add(new TypeCatalog.Type(type.getCode(), type.getJavaClassName(), type.getSourcePath(), + type.getSourceLine(), attributes)); + } + cached = new TypeCatalog(types); + previous = snapshot; + } + return cached; + } + + @Override + public Location resolveLocation(final String documentUri, final String sourcePath, final int sourceLine) { + final Path root = documentRoot(documentUri); + if (root == null || sourcePath == null || sourceLine < 1) { + return null; + } + final IFile file; + try { + final IPath path = org.eclipse.core.runtime.Path.fromPortableString(sourcePath); + if (!path.isAbsolute() || path.segmentCount() < 2) { + return null; + } + file = workspace.getRoot().getFile(path); + } catch (final IllegalArgumentException e) { + return null; + } + if (!file.isAccessible() || file.getLocation() == null || file.getLocationURI() == null + || !file.getLocation().toFile().toPath().toAbsolutePath().normalize().startsWith(root)) { + return null; + } + final Position line = new Position(sourceLine - 1, 0); + return new Location(file.getLocationURI().toString(), new Range(line, new Position(sourceLine - 1, 0))); + } + + private Path documentRoot(final String documentUri) { + if (documentUri == null) { + return null; + } + final IProject platform = workspace.getRoot().getProject(Constants.PLATFROM); + if (!platform.isAccessible() || platform.getLocation() == null) { + return null; + } + final URI uri; + try { + uri = URI.create(documentUri); + } catch (final IllegalArgumentException e) { + return null; + } + if (!"file".equals(uri.getScheme()) || uri.isOpaque() || uri.getPath() == null //$NON-NLS-1$ + || uri.getQuery() != null || uri.getFragment() != null) { + return null; + } + final IFile[] files = workspace.getRoot().findFilesForLocationURI(uri); + if (files.length != 1 || !files[0].isAccessible() || files[0].getLocation() == null) { + return null; + } + Path root = platform.getLocation().toFile().toPath().toAbsolutePath().normalize(); + // Only the standard hybris/bin/platform layout establishes a wider Commerce tree. + if (root.getFileName().toString().equals(Constants.PLATFROM) && root.getParent() != null + && root.getParent().getParent() != null && root.getParent().getParent().getParent() != null + && "bin".equals(root.getParent().getFileName().toString())) { //$NON-NLS-1$ + root = root.getParent().getParent(); + } + return root != null && files[0].getLocation().toFile().toPath().toAbsolutePath().normalize().startsWith(root) + ? root : null; + } +} diff --git a/docs/dev/impex/editor-replacement-plan.md b/docs/dev/impex/editor-replacement-plan.md index c0c33023..788af287 100644 --- a/docs/dev/impex/editor-replacement-plan.md +++ b/docs/dev/impex/editor-replacement-plan.md @@ -39,8 +39,21 @@ Status: migration started on `feature/impex-lsp-migration`; legacy editor retain - Formatting verification: all 133 tests passed in the full 21-module reactor, including 42 ImpEx tests. The p2 ZIP contains both editor bundles, the language server, and its connection provider. Live shortcut/focus and upgrade checks remain. -- Next: project-scoped type-system completion/navigation, macro assistance, - symbols/diagnostics, and interactive UI/upgrade checks. TextMate continuation +- Added context-aware LSP completion and definition navigation using a workspace + adapter to the shared type index, without introducing UI dependencies into the + language server. Includes inherited/nested reference attributes, modifier names + and values, precise token replacement, and earlier document-local macro proposals. +- The adapter explicitly scopes the current single `platform` index to its Commerce + tree. Other roots and ambiguous aliases receive no indexed types; external + extensions and full multi-platform indexing remain limitations. Source navigation + checks workspace accessibility instead of guessing class/file locations. +- Tests cover metadata refresh, distinct document catalogs, inaccessible/deleted + sources, UTF-16 ranges, stale requests, cancellation, and real JSON-RPC assistance. +- Completion/navigation verification: all 156 tests passed in the full reactor, + including 65 ImpEx tests. The p2 ZIP contains the language features, scoped + workspace adapter, and localized proposal descriptions. Live content-assist, + hyperlink, and multi-platform workflow checks remain outstanding. +- Next: macro hover, symbols/diagnostics, and interactive UI/upgrade checks. TextMate continuation highlighting still needs refinement. The legacy editor must not be retired yet. ## Goal and scope From 2882efecd459b2503f8cac80818ea437d4ed9ed9 Mon Sep 17 00:00:00 2001 From: Pawel Wolanski Date: Sat, 21 Nov 2026 04:17:43 +0100 Subject: [PATCH 06/25] feat(impex): add hover, symbols and diagnostics Show source metadata without executing macro definitions. Publish only confirmed CSV quote errors from current snapshots. Coalesce edit notifications and clear markers on correction or close. Negotiate symbol response format with the language client. --- com.hybris.hyeclipse.impex.ls/README.md | 27 ++- .../impex/ls/ImpexLanguageServer.java | 132 +++++++++++++- .../impex/ls/format/ImpexCsvScanner.java | 25 ++- .../impex/ls/types/ImpexDocumentAnalysis.java | 140 +++++++++++++++ .../impex/ls/types/ImpexLanguageFeatures.java | 78 ++++++++- .../hyeclipse/impex/ls/types/Messages.java | 6 + .../impex/ls/types/Messages.properties | 6 + .../tests/ImpexDiagnosticsServiceTest.java | 164 ++++++++++++++++++ .../tests/ImpexDocumentAnalysisTest.java | 150 ++++++++++++++++ .../impex/tests/ImpexLanguageServerTest.java | 36 +++- com.hybris.hyeclipse.impex/README.md | 14 +- .../impex/lsp/ImpexConnectionProvider.java | 8 +- docs/dev/impex/editor-replacement-plan.md | 9 +- 13 files changed, 771 insertions(+), 24 deletions(-) create mode 100644 com.hybris.hyeclipse.impex.ls/src/com/hybris/hyeclipse/impex/ls/types/ImpexDocumentAnalysis.java create mode 100644 com.hybris.hyeclipse.impex.tests/src/com/hybris/hyeclipse/impex/tests/ImpexDiagnosticsServiceTest.java create mode 100644 com.hybris.hyeclipse.impex.tests/src/com/hybris/hyeclipse/impex/tests/ImpexDocumentAnalysisTest.java diff --git a/com.hybris.hyeclipse.impex.ls/README.md b/com.hybris.hyeclipse.impex.ls/README.md index 457f7adc..ea2ab7dc 100644 --- a/com.hybris.hyeclipse.impex.ls/README.md +++ b/com.hybris.hyeclipse.impex.ls/README.md @@ -2,7 +2,8 @@ Non-UI LSP4J bundle, connected in-process through the preview bundle's LSP4E provider. Full document synchronization, UTF-16 positions, document/range formatting, -completion, and definition navigation are advertised. The server analyzes open +completion, definition navigation, hover, and document symbols are advertised. +Quote diagnostics are pushed to the client. The server analyzes open snapshots and host-supplied metadata; it does not load files, connect to Commerce, or execute scripts. @@ -48,10 +49,30 @@ or execute scripts. Closed, superseded, or cancelled requests cannot supply edits for old snapshots. LSP4E also rejects results when the editor document's modification stamp changed. +## Hover, outline, and diagnostics + +- Hover shows indexed type/attribute details or the current/latest earlier macro + source definition. Definitions are not evaluated. Content is bounded to about + 2 Ki UTF-16 units and sent as plain text, not interpreted Markdown/HTML. +- Header/macro symbols identify lexical declarations, not runtime block scopes. + Header ranges cover declarations only; duplicate macro definitions remain separate + entries. Flat or hierarchical symbol response formats follow client capabilities. + At most 1,000 symbols are returned. +- Diagnostics use push notifications, supported by the target LSP4E release. + A separate single-worker pump coalesces rapid changes per document, checks snapshot + identity before publication, includes document versions, and clears results on + correction or close. It does not fill the language-request queue with edit events. +- Only unmatched opening quotes at EOF and unexpected characters after closing + cell quotes are reported. Ranges point to the opening quote or offending character + using UTF-16 positions. At most 100 confirmed quote errors are reported per document. +- Unknown types/macros, row/header cell counts, modifiers, translators, scripting, + and import outcomes are not validated. Oversized/unsupported analysis produces no + inferred errors. No ImpEx code is executed to compute any result. + Parser rules follow `docs/dev/impex/impex-docs.md`, not RFC 4180: quotes only start at cell boundaries, doubled quotes are literal, and backslashes do not escape quotes. The scanner groups continued/multiline records for safety, but does not implement the full import engine or header execution semantics. -Macro hover, symbols, diagnostics, and UI/upgrade checks are subsequent slices. -See [the migration plan](../docs/dev/impex/editor-replacement-plan.md). +UI/upgrade checks, CSV/header compatibility refinements, and multi-platform indexing +remain outstanding. See [the migration plan](../docs/dev/impex/editor-replacement-plan.md). diff --git a/com.hybris.hyeclipse.impex.ls/src/com/hybris/hyeclipse/impex/ls/ImpexLanguageServer.java b/com.hybris.hyeclipse.impex.ls/src/com/hybris/hyeclipse/impex/ls/ImpexLanguageServer.java index fd71da5f..49cd32e4 100644 --- a/com.hybris.hyeclipse.impex.ls/src/com/hybris/hyeclipse/impex/ls/ImpexLanguageServer.java +++ b/com.hybris.hyeclipse.impex.ls/src/com/hybris/hyeclipse/impex/ls/ImpexLanguageServer.java @@ -11,6 +11,7 @@ import java.util.ArrayList; import java.util.Arrays; +import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; @@ -28,6 +29,7 @@ import org.eclipse.lsp4j.CompletionOptions; import org.eclipse.lsp4j.CompletionParams; import org.eclipse.lsp4j.DefinitionParams; +import org.eclipse.lsp4j.Diagnostic; import org.eclipse.lsp4j.DidChangeConfigurationParams; import org.eclipse.lsp4j.DidChangeTextDocumentParams; import org.eclipse.lsp4j.DidChangeWatchedFilesParams; @@ -36,21 +38,30 @@ import org.eclipse.lsp4j.DidSaveTextDocumentParams; import org.eclipse.lsp4j.DocumentFormattingParams; import org.eclipse.lsp4j.DocumentRangeFormattingParams; +import org.eclipse.lsp4j.DocumentSymbol; +import org.eclipse.lsp4j.DocumentSymbolParams; +import org.eclipse.lsp4j.Hover; +import org.eclipse.lsp4j.HoverParams; import org.eclipse.lsp4j.InitializeParams; import org.eclipse.lsp4j.InitializeResult; import org.eclipse.lsp4j.Location; import org.eclipse.lsp4j.LocationLink; import org.eclipse.lsp4j.PositionEncodingKind; +import org.eclipse.lsp4j.PublishDiagnosticsParams; import org.eclipse.lsp4j.ServerCapabilities; +import org.eclipse.lsp4j.SymbolInformation; import org.eclipse.lsp4j.TextDocumentContentChangeEvent; import org.eclipse.lsp4j.TextDocumentSyncKind; import org.eclipse.lsp4j.TextEdit; import org.eclipse.lsp4j.jsonrpc.messages.Either; +import org.eclipse.lsp4j.services.LanguageClient; +import org.eclipse.lsp4j.services.LanguageClientAware; import org.eclipse.lsp4j.services.LanguageServer; import org.eclipse.lsp4j.services.TextDocumentService; import org.eclipse.lsp4j.services.WorkspaceService; import com.hybris.hyeclipse.impex.ls.format.ImpexFormatter; +import com.hybris.hyeclipse.impex.ls.types.ImpexDocumentAnalysis; import com.hybris.hyeclipse.impex.ls.types.ImpexLanguageFeatures; import com.hybris.hyeclipse.impex.ls.types.ImpexLanguageFeatures.SourceTarget; import com.hybris.hyeclipse.impex.ls.types.TypeCatalog; @@ -58,7 +69,7 @@ /** In-memory ImpEx language services; host metadata is supplied through a non-UI adapter boundary. */ public final class ImpexLanguageServer - implements LanguageServer, TextDocumentService, WorkspaceService, AutoCloseable { + implements LanguageServer, TextDocumentService, WorkspaceService, LanguageClientAware, AutoCloseable { private static final int MAX_PENDING_REQUESTS = 8; private final Map documents = new ConcurrentHashMap<>(); @@ -71,6 +82,16 @@ public final class ImpexLanguageServer return thread; }); private volatile boolean closed; + private LanguageClient client; + private final Set dirtyDiagnostics = new LinkedHashSet<>(); + private boolean diagnosticsRunning; + private volatile boolean hierarchicalSymbols; + private final ThreadPoolExecutor diagnosticExecutor = new ThreadPoolExecutor(1, 1, 0, TimeUnit.MILLISECONDS, + new ArrayBlockingQueue<>(1), runnable -> { + final Thread thread = new Thread(runnable, "ImpEx diagnostics"); //$NON-NLS-1$ + thread.setDaemon(true); + return thread; + }); /** Creates syntax-only services for hosts without a type-system adapter. */ public ImpexLanguageServer() { @@ -94,6 +115,10 @@ private DocumentSnapshot(final String text, final int version) { @Override public CompletableFuture initialize(final InitializeParams params) { + hierarchicalSymbols = params.getCapabilities() != null && params.getCapabilities().getTextDocument() != null + && params.getCapabilities().getTextDocument().getDocumentSymbol() != null + && Boolean.TRUE.equals(params.getCapabilities().getTextDocument().getDocumentSymbol() + .getHierarchicalDocumentSymbolSupport()); final ServerCapabilities capabilities = new ServerCapabilities(); capabilities.setTextDocumentSync(TextDocumentSyncKind.Full); capabilities.setPositionEncoding(PositionEncodingKind.UTF16); @@ -102,6 +127,8 @@ public CompletableFuture initialize(final InitializeParams par capabilities.setCompletionProvider(new CompletionOptions(false, Arrays.asList(";", "(", "[", ",", ".", "$", "="))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ capabilities.setDefinitionProvider(true); + capabilities.setHoverProvider(true); + capabilities.setDocumentSymbolProvider(true); return CompletableFuture.completedFuture(new InitializeResult(capabilities)); } @@ -126,11 +153,22 @@ public WorkspaceService getWorkspaceService() { return this; } + @Override + public synchronized void connect(final LanguageClient client) { + if (!closed) { + this.client = client; + dirtyDiagnostics.addAll(documents.keySet()); + startDiagnostics(); + } + } + @Override public synchronized void didOpen(final DidOpenTextDocumentParams params) { if (!closed) { documents.put(params.getTextDocument().getUri(), new DocumentSnapshot(params.getTextDocument().getText(), params.getTextDocument().getVersion())); + dirtyDiagnostics.add(params.getTextDocument().getUri()); + startDiagnostics(); } } @@ -146,17 +184,24 @@ public synchronized void didChange(final DidChangeTextDocumentParams params) { for (final TextDocumentContentChangeEvent change : params.getContentChanges()) { if (change.getRange() != null) { documents.remove(uri); + dirtyDiagnostics.remove(uri); + publish(new PublishDiagnosticsParams(uri, new ArrayList<>())); return; } } if (!params.getContentChanges().isEmpty()) { documents.put(uri, new DocumentSnapshot(params.getContentChanges().getLast().getText(), version)); + dirtyDiagnostics.add(uri); + startDiagnostics(); } } @Override public synchronized void didClose(final DidCloseTextDocumentParams params) { - documents.remove(params.getTextDocument().getUri()); + final String uri = params.getTextDocument().getUri(); + documents.remove(uri); + dirtyDiagnostics.remove(uri); + publish(new PublishDiagnosticsParams(uri, new ArrayList<>())); } @Override @@ -215,6 +260,86 @@ public CompletableFuture, List hover(final HoverParams params) { + final String uri = params.getTextDocument().getUri(); + return request(uri, null, (snapshot, cancelled) -> { + final TypeCatalog catalog = types.getCatalog(uri); + final Hover hover = new ImpexLanguageFeatures().hover(snapshot.text, params.getPosition(), catalog, cancelled); + return types.getCatalog(uri) == catalog ? hover : null; + }); + } + + @Override + public CompletableFuture>> documentSymbol( + final DocumentSymbolParams params) { + return request(params.getTextDocument().getUri(), new ArrayList<>(), (snapshot, cancelled) -> { + final List> symbols = new ArrayList<>(); + for (final DocumentSymbol symbol : new ImpexDocumentAnalysis().symbols(snapshot.text, cancelled)) { + if (hierarchicalSymbols) { + symbols.add(Either.forRight(symbol)); + } else { + symbols.add(Either.forLeft(new SymbolInformation(symbol.getName(), symbol.getKind(), + new Location(params.getTextDocument().getUri(), symbol.getSelectionRange())))); + } + } + return symbols; + }); + } + + // One pump coalesces all document changes; notification bursts cannot fill the request queue. + private void startDiagnostics() { + if (closed || client == null || diagnosticsRunning || dirtyDiagnostics.isEmpty()) { + return; + } + diagnosticsRunning = true; + diagnosticExecutor.execute(this::drainDiagnostics); + } + + private void drainDiagnostics() { + try { + while (true) { + final String uri; + final DocumentSnapshot snapshot; + synchronized (this) { + if (closed || client == null || dirtyDiagnostics.isEmpty()) { + return; + } + uri = dirtyDiagnostics.iterator().next(); + dirtyDiagnostics.remove(uri); + snapshot = documents.get(uri); + } + if (snapshot == null) { + continue; + } + final List diagnostics = new ImpexDocumentAnalysis().diagnostics(snapshot.text, + () -> closed || documents.get(uri) != snapshot); + synchronized (this) { + if (!closed && documents.get(uri) == snapshot) { + publish(new PublishDiagnosticsParams(uri, diagnostics, snapshot.version)); + } + } + } + } finally { + synchronized (this) { + diagnosticsRunning = false; + startDiagnostics(); + } + } + } + + // All publications are serialized with document updates/close to prevent late obsolete markers. + private void publish(final PublishDiagnosticsParams params) { + if (!closed && client != null) { + try { + client.publishDiagnostics(params); + } catch (final RuntimeException e) { + // A disconnected transport cannot receive notifications; reconnect supplies a new client. + client = null; + } + } + } + private Either, CompletionList> completionReply(final CompletionList list) { return Either.forRight(list); } @@ -255,9 +380,12 @@ private synchronized CompletableFuture request(final String uri, final T public synchronized void close() { closed = true; documents.clear(); + dirtyDiagnostics.clear(); + client = null; for (final CompletableFuture request : pending) { request.cancel(true); } executor.shutdownNow(); + diagnosticExecutor.shutdownNow(); } } diff --git a/com.hybris.hyeclipse.impex.ls/src/com/hybris/hyeclipse/impex/ls/format/ImpexCsvScanner.java b/com.hybris.hyeclipse.impex.ls/src/com/hybris/hyeclipse/impex/ls/format/ImpexCsvScanner.java index e86a2783..6b3f7db4 100644 --- a/com.hybris.hyeclipse.impex.ls/src/com/hybris/hyeclipse/impex/ls/format/ImpexCsvScanner.java +++ b/com.hybris.hyeclipse.impex.ls/src/com/hybris/hyeclipse/impex/ls/format/ImpexCsvScanner.java @@ -37,15 +37,19 @@ public static final class CsvRecord { private final boolean valid; private final boolean multiline; private final Kind kind; + private final int textAfterQuote; + private final int unclosedQuote; private CsvRecord(final int start, final int contentEnd, final int end, final List cells, - final boolean valid, final boolean multiline) { + final boolean valid, final boolean multiline, final int textAfterQuote, final int unclosedQuote) { this.start = start; this.contentEnd = contentEnd; this.end = end; this.cells = Collections.unmodifiableList(new ArrayList<>(cells)); this.valid = valid; this.multiline = multiline; + this.textAfterQuote = textAfterQuote; + this.unclosedQuote = unclosedQuote; final String first = valueOf(cells.get(0)); if (first.startsWith("#%")) { //$NON-NLS-1$ kind = Kind.SCRIPT; @@ -78,6 +82,10 @@ private CsvRecord(final int start, final int contentEnd, final int end, final Li public boolean isMultiline() { return multiline; } /** @return lexical record kind */ public Kind getKind() { return kind; } + /** @return first offending character after a closing quote, or -1 when absent */ + public int getTextAfterQuote() { return textAfterQuote; } + /** @return opening quote still unmatched at EOF, or -1 when absent */ + public int getUnclosedQuote() { return unclosedQuote; } } /** @@ -123,6 +131,8 @@ public List scan(final String source, final BooleanSupplier cancelled boolean cellEnded = false; boolean valid = true; boolean multiline = false; + int quoteStart = -1; + int textAfterQuote = -1; for (int i = 0; i < source.length(); i++) { if (i % CANCELLATION_INTERVAL == 0 && cancelled.getAsBoolean()) { return new ArrayList<>(); @@ -137,7 +147,8 @@ public List scan(final String source, final BooleanSupplier cancelled continue; } cells.add(source.substring(cellStart, i)); - add(records, new CsvRecord(recordStart, i, i + delimiterLength, cells, valid, multiline)); + add(records, new CsvRecord(recordStart, i, i + delimiterLength, cells, valid, multiline, + textAfterQuote, -1)); i += delimiterLength - 1; recordStart = i + 1; cellStart = recordStart; @@ -146,12 +157,15 @@ public List scan(final String source, final BooleanSupplier cancelled cellEnded = false; valid = true; multiline = false; + quoteStart = -1; + textAfterQuote = -1; } else if (quoted) { if (c == '"') { if (i + 1 < source.length() && source.charAt(i + 1) == '"') { i++; } else { quoted = false; + quoteStart = -1; cellEnded = true; } } @@ -165,10 +179,14 @@ public List scan(final String source, final BooleanSupplier cancelled cellEnded = false; } else if (c == '"' && !cellStarted) { quoted = true; + quoteStart = i; cellStarted = true; } else if (!Character.isWhitespace(c)) { if (cellEnded) { valid = false; + if (textAfterQuote < 0) { + textAfterQuote = i; + } } cellStarted = true; } @@ -177,7 +195,8 @@ public List scan(final String source, final BooleanSupplier cancelled cells.add(source.substring(cellStart)); // A final continuation marker without a following line is ambiguous to format. valid = valid && !quoted && !source.endsWith("\\"); //$NON-NLS-1$ - add(records, new CsvRecord(recordStart, source.length(), source.length(), cells, valid, multiline)); + add(records, new CsvRecord(recordStart, source.length(), source.length(), cells, valid, multiline, + textAfterQuote, quoted ? quoteStart : -1)); } return records; } diff --git a/com.hybris.hyeclipse.impex.ls/src/com/hybris/hyeclipse/impex/ls/types/ImpexDocumentAnalysis.java b/com.hybris.hyeclipse.impex.ls/src/com/hybris/hyeclipse/impex/ls/types/ImpexDocumentAnalysis.java new file mode 100644 index 00000000..beccbe4c --- /dev/null +++ b/com.hybris.hyeclipse.impex.ls/src/com/hybris/hyeclipse/impex/ls/types/ImpexDocumentAnalysis.java @@ -0,0 +1,140 @@ +/******************************************************************************* + * Copyright 2020 SAP + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + ******************************************************************************/ +package com.hybris.hyeclipse.impex.ls.types; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.BooleanSupplier; +import java.util.regex.Matcher; + +import org.eclipse.lsp4j.Diagnostic; +import org.eclipse.lsp4j.DiagnosticSeverity; +import org.eclipse.lsp4j.DocumentSymbol; +import org.eclipse.lsp4j.Range; +import org.eclipse.lsp4j.SymbolKind; + +import com.hybris.hyeclipse.impex.ls.format.ImpexCsvScanner; +import com.hybris.hyeclipse.impex.ls.format.ImpexCsvScanner.CsvRecord; +import com.hybris.hyeclipse.impex.ls.format.ImpexCsvScanner.Kind; +import com.hybris.hyeclipse.impex.ls.format.TextPositions; + +/** Source-only outline and confirmed CSV quote diagnostics, independent of the Commerce index. */ +public final class ImpexDocumentAnalysis { + + private static final int MAX_SYMBOLS = 1000; + private static final int MAX_DIAGNOSTICS = 100; + + /** + * @param text document snapshot + * @param cancelled cancellation predicate + * @return lexical header/macro declarations in source order, not inferred runtime scopes + */ + public List symbols(final String text, final BooleanSupplier cancelled) { + final List symbols = new ArrayList<>(); + if (text.length() > ImpexCsvScanner.MAX_DOCUMENT_LENGTH || cancelled.getAsBoolean()) { + return symbols; + } + final List records; + try { + records = new ImpexCsvScanner().scan(text, cancelled); + } catch (final IllegalArgumentException e) { + return symbols; + } + final TextPositions positions = new TextPositions(text); + for (final CsvRecord record : records) { + if (cancelled.getAsBoolean()) { + return new ArrayList<>(); + } + if (!record.isValid()) { + continue; + } + final String raw = record.getCells().getFirst(); + int start = 0; + while (start < raw.length() && raw.charAt(start) <= ' ') { + start++; + } + if (start < raw.length() && raw.charAt(start) == '"') { + start++; + } + final String first = raw.substring(start); + final int base = record.getStart() + start; + final Range range = new Range(positions.positionAt(record.getStart()), + positions.positionAt(record.getContentEnd())); + if (record.getKind() == Kind.MACRO) { + final Matcher macro = ImpexLanguageFeatures.MACRO.matcher(first); + if (macro.find()) { + symbols.add(new DocumentSymbol(macro.group(1), SymbolKind.Variable, range, + new Range(positions.positionAt(base + macro.start(1)), + positions.positionAt(base + macro.end(1))))); + } + } else if (record.getKind() == Kind.HEADER && !record.isMultiline()) { + final Matcher mode = ImpexLanguageFeatures.MODE.matcher(first); + if (mode.find()) { + int end = mode.end(); + while (end < first.length() && ImpexLanguageFeatures.nameChar(first.charAt(end), true)) { + end++; + } + if (end > mode.end()) { + symbols.add(new DocumentSymbol(mode.group(1) + " " + first.substring(mode.end(), end), //$NON-NLS-1$ + SymbolKind.Class, range, new Range(positions.positionAt(base + mode.end()), + positions.positionAt(base + end)))); + } + } + } + if (symbols.size() >= MAX_SYMBOLS) { + break; + } + } + return cancelled.getAsBoolean() ? new ArrayList<>() : symbols; + } + + /** + * @param text document snapshot + * @param cancelled cancellation predicate + * @return confirmed quote errors only; no type, macro, modifier, or import-result validation + */ + public List diagnostics(final String text, final BooleanSupplier cancelled) { + final List diagnostics = new ArrayList<>(); + if (text.length() > ImpexCsvScanner.MAX_DOCUMENT_LENGTH || cancelled.getAsBoolean()) { + return diagnostics; + } + final List records; + try { + records = new ImpexCsvScanner().scan(text, cancelled); + } catch (final IllegalArgumentException e) { + return diagnostics; + } + final TextPositions positions = new TextPositions(text); + for (final CsvRecord record : records) { + if (cancelled.getAsBoolean()) { + return new ArrayList<>(); + } + if (record.getTextAfterQuote() >= 0) { + add(diagnostics, text, positions, record.getTextAfterQuote(), "impex.textAfterQuote", Messages.textAfterQuote); //$NON-NLS-1$ + } + if (record.getUnclosedQuote() >= 0 && diagnostics.size() < MAX_DIAGNOSTICS) { + add(diagnostics, text, positions, record.getUnclosedQuote(), "impex.unclosedQuote", Messages.unclosedQuote); //$NON-NLS-1$ + } + if (diagnostics.size() >= MAX_DIAGNOSTICS) { + break; + } + } + return cancelled.getAsBoolean() ? new ArrayList<>() : diagnostics; + } + + private void add(final List diagnostics, final String text, final TextPositions positions, + final int offset, final String code, final String message) { + final int end = offset + Character.charCount(text.codePointAt(offset)); + final Diagnostic diagnostic = new Diagnostic(new Range(positions.positionAt(offset), positions.positionAt(end)), + message, DiagnosticSeverity.Error, "ImpEx"); //$NON-NLS-1$ + diagnostic.setCode(code); + diagnostics.add(diagnostic); + } +} diff --git a/com.hybris.hyeclipse.impex.ls/src/com/hybris/hyeclipse/impex/ls/types/ImpexLanguageFeatures.java b/com.hybris.hyeclipse.impex.ls/src/com/hybris/hyeclipse/impex/ls/types/ImpexLanguageFeatures.java index b050f841..d246e90a 100644 --- a/com.hybris.hyeclipse.impex.ls/src/com/hybris/hyeclipse/impex/ls/types/ImpexLanguageFeatures.java +++ b/com.hybris.hyeclipse.impex.ls/src/com/hybris/hyeclipse/impex/ls/types/ImpexLanguageFeatures.java @@ -23,10 +23,14 @@ import org.eclipse.lsp4j.CompletionItem; import org.eclipse.lsp4j.CompletionItemKind; import org.eclipse.lsp4j.CompletionList; +import org.eclipse.lsp4j.Hover; +import org.eclipse.lsp4j.MarkupContent; +import org.eclipse.lsp4j.MarkupKind; import org.eclipse.lsp4j.Position; import org.eclipse.lsp4j.Range; import org.eclipse.lsp4j.TextEdit; import org.eclipse.lsp4j.jsonrpc.messages.Either; +import org.eclipse.osgi.util.NLS; import com.hybris.hyeclipse.impex.ls.format.ImpexCsvScanner; import com.hybris.hyeclipse.impex.ls.format.ImpexCsvScanner.CsvRecord; @@ -39,8 +43,9 @@ public final class ImpexLanguageFeatures { private static final int MAX_PROPOSALS = 200; - private static final Pattern MODE = Pattern.compile("(?i)^\\s*(INSERT_UPDATE|INSERT|UPDATE|REMOVE)(?:\\s+|$)"); //$NON-NLS-1$ - private static final Pattern MACRO = Pattern.compile("^\\s*(\\$[\\w-]+)\\s*="); //$NON-NLS-1$ + private static final int MAX_HOVER_TEXT = 2048; + static final Pattern MODE = Pattern.compile("(?i)^\\s*(INSERT_UPDATE|INSERT|UPDATE|REMOVE)(?:\\s+|$)"); //$NON-NLS-1$ + static final Pattern MACRO = Pattern.compile("^\\s*(\\$[\\w-]+)\\s*="); //$NON-NLS-1$ private static final List OPERATIONS = Arrays.asList("INSERT", "INSERT_UPDATE", "REMOVE", "UPDATE"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ private static final List HEADER_MODIFIERS = Arrays.asList("batchmode", "cacheUnique", "processor", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ "parallel", "ignoreKeyCase", "unlessExisting", "impex.legacy.mode", "sld.enabled", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ @@ -218,6 +223,73 @@ public SourceTarget definition(final String text, final Position position, final return null; } + /** + * @param text open document snapshot + * @param position requested UTF-16 position + * @param catalog document-scoped metadata + * @param cancelled cancellation/stale-document predicate + * @return plain-text type, attribute, or macro information; null for unknown contexts + */ + public Hover hover(final String text, final Position position, final TypeCatalog catalog, + final BooleanSupplier cancelled) { + if (text.length() > ImpexCsvScanner.MAX_DOCUMENT_LENGTH || cancelled.getAsBoolean()) { + return null; + } + final TextPositions positions = new TextPositions(text); + final int offset; + final List records; + try { + offset = positions.offsetAt(position); + records = new ImpexCsvScanner().scan(text, cancelled); + } catch (final IllegalArgumentException e) { + return null; + } + final Context context = context(text, offset, records, catalog); + String description = null; + if (context.area == Area.TYPE) { + final Type type = catalog.getType(context.token.text); + if (type != null) { + description = NLS.bind(Messages.typeHover, type.getCode(), type.getJavaClass()); + } + } else if (context.area == Area.ATTRIBUTE && context.type != null) { + final Attribute attribute = context.type.getAttribute(context.token.text); + if (attribute != null) { + description = NLS.bind(Messages.attributeHover, + new Object[] {context.type.getCode(), attribute.getName(), attribute.getJavaType()}); + } + } else if (context.area == Area.MACRO) { + for (final CsvRecord record : records) { + if (cancelled.getAsBoolean()) { + return null; + } + if (record.isValid() && record.getKind() == Kind.MACRO) { + final Matcher macro = MACRO.matcher(ImpexCsvScanner.valueOf(record.getCells().getFirst())); + final boolean earlier = record.getEnd() <= offset && record.getContentEnd() < offset; + final boolean declaration = context.token.start >= record.getStart() + && context.token.end <= record.getStart() + record.getCells().getFirst().indexOf('='); + if ((earlier || declaration) && macro.find() && macro.group(1).equals(context.token.text)) { + final int end = Math.min(record.getContentEnd(), record.getStart() + MAX_HOVER_TEXT); + final String definition = text.substring(record.getStart(), end) + + (end < record.getContentEnd() ? Messages.truncated : ""); //$NON-NLS-1$ + description = NLS.bind(Messages.macroHover, context.token.text, definition); + } + } + } + } + if (description == null || cancelled.getAsBoolean()) { + return null; + } + if (description.length() > MAX_HOVER_TEXT) { + int end = MAX_HOVER_TEXT; + if (Character.isHighSurrogate(description.charAt(end - 1)) && Character.isLowSurrogate(description.charAt(end))) { + end--; + } + description = description.substring(0, end) + Messages.truncated; + } + return new Hover(new MarkupContent(MarkupKind.PLAINTEXT, description), + new Range(positions.positionAt(context.token.start), positions.positionAt(context.token.end))); + } + /** @return an empty, complete proposal list */ public static CompletionList emptyCompletion() { return new CompletionList(false, new ArrayList<>()); @@ -374,7 +446,7 @@ private Type reference(final TypeCatalog catalog, final Type type, final String return attribute == null ? null : catalog.referenceType(attribute.getJavaType()); } - private static boolean nameChar(final char c, final boolean dots) { + static boolean nameChar(final char c, final boolean dots) { return Character.isLetterOrDigit(c) || c == '_' || c == '-' || c == '$' || (dots && c == '.'); } diff --git a/com.hybris.hyeclipse.impex.ls/src/com/hybris/hyeclipse/impex/ls/types/Messages.java b/com.hybris.hyeclipse.impex.ls/src/com/hybris/hyeclipse/impex/ls/types/Messages.java index 18749948..b36f12bb 100644 --- a/com.hybris.hyeclipse.impex.ls/src/com/hybris/hyeclipse/impex/ls/types/Messages.java +++ b/com.hybris.hyeclipse.impex.ls/src/com/hybris/hyeclipse/impex/ls/types/Messages.java @@ -17,6 +17,12 @@ final class Messages extends NLS { public static String headerModifier; public static String columnModifier; public static String modifierValue; + public static String typeHover; + public static String attributeHover; + public static String macroHover; + public static String truncated; + public static String unclosedQuote; + public static String textAfterQuote; static { NLS.initializeMessages("com.hybris.hyeclipse.impex.ls.types.Messages", Messages.class); //$NON-NLS-1$ diff --git a/com.hybris.hyeclipse.impex.ls/src/com/hybris/hyeclipse/impex/ls/types/Messages.properties b/com.hybris.hyeclipse.impex.ls/src/com/hybris/hyeclipse/impex/ls/types/Messages.properties index 2573c6f3..aec5f0e3 100644 --- a/com.hybris.hyeclipse.impex.ls/src/com/hybris/hyeclipse/impex/ls/types/Messages.properties +++ b/com.hybris.hyeclipse.impex.ls/src/com/hybris/hyeclipse/impex/ls/types/Messages.properties @@ -3,3 +3,9 @@ macro=ImpEx macro defined earlier in this document headerModifier=ImpEx header modifier columnModifier=ImpEx column modifier modifierValue=ImpEx modifier value +typeHover={0}\nGenerated model: {1} +attributeHover={0}.{1}\nJava type: {2} +macroHover={0}\nSource definition (not evaluated):\n{1} +truncated=... (truncated) +unclosedQuote=Unclosed quoted ImpEx cell. Close the quote or use doubled quotes for a literal quote. +textAfterQuote=Unexpected text after a closing quote; only whitespace or a cell separator may follow. diff --git a/com.hybris.hyeclipse.impex.tests/src/com/hybris/hyeclipse/impex/tests/ImpexDiagnosticsServiceTest.java b/com.hybris.hyeclipse.impex.tests/src/com/hybris/hyeclipse/impex/tests/ImpexDiagnosticsServiceTest.java new file mode 100644 index 00000000..48d075a8 --- /dev/null +++ b/com.hybris.hyeclipse.impex.tests/src/com/hybris/hyeclipse/impex/tests/ImpexDiagnosticsServiceTest.java @@ -0,0 +1,164 @@ +/******************************************************************************* + * Copyright 2020 SAP + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + ******************************************************************************/ +package com.hybris.hyeclipse.impex.tests; + +import java.lang.reflect.Proxy; +import java.util.Arrays; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; + +import org.eclipse.lsp4j.ClientCapabilities; +import org.eclipse.lsp4j.DidChangeTextDocumentParams; +import org.eclipse.lsp4j.DidCloseTextDocumentParams; +import org.eclipse.lsp4j.DidOpenTextDocumentParams; +import org.eclipse.lsp4j.DocumentSymbolCapabilities; +import org.eclipse.lsp4j.DocumentSymbolParams; +import org.eclipse.lsp4j.HoverParams; +import org.eclipse.lsp4j.InitializeParams; +import org.eclipse.lsp4j.Position; +import org.eclipse.lsp4j.PublishDiagnosticsParams; +import org.eclipse.lsp4j.TextDocumentClientCapabilities; +import org.eclipse.lsp4j.TextDocumentContentChangeEvent; +import org.eclipse.lsp4j.TextDocumentIdentifier; +import org.eclipse.lsp4j.TextDocumentItem; +import org.eclipse.lsp4j.VersionedTextDocumentIdentifier; +import org.eclipse.lsp4j.services.LanguageClient; +import org.junit.Assert; +import org.junit.Test; + +import com.hybris.hyeclipse.impex.ls.ImpexLanguageServer; + +public class ImpexDiagnosticsServiceTest { + + private static final String URI = "file:///diagnostics.impex"; + private static final String INVALID = "INSERT T;a;b\n;id;\"unclosed"; + private static final String VALID = "INSERT T;a;b\n;id;value"; + + @Test + public void publishesQuoteErrorsAndClearsThemAfterCorrectionAndClose() throws Exception { + final BlockingQueue notifications = new LinkedBlockingQueue<>(); + try (final ImpexLanguageServer server = new ImpexLanguageServer()) { + server.connect(client(notifications)); + open(server, 1, INVALID); + final PublishDiagnosticsParams error = next(notifications); + Assert.assertEquals(Integer.valueOf(1), error.getVersion()); + Assert.assertEquals("impex.unclosedQuote", error.getDiagnostics().getFirst().getCode().getLeft()); + change(server, 2, VALID); + final PublishDiagnosticsParams corrected = next(notifications); + Assert.assertEquals(Integer.valueOf(2), corrected.getVersion()); + Assert.assertTrue(corrected.getDiagnostics().isEmpty()); + server.didClose(new DidCloseTextDocumentParams(new TextDocumentIdentifier(URI))); + final PublishDiagnosticsParams closed = next(notifications); + Assert.assertNull(closed.getVersion()); + Assert.assertTrue(closed.getDiagnostics().isEmpty()); + } + } + + @Test + public void coalescesRapidChangesAndDoesNotPublishOldMarkersAfterReopening() throws Exception { + final BlockingQueue notifications = new LinkedBlockingQueue<>(); + try (final ImpexLanguageServer server = new ImpexLanguageServer()) { + server.connect(client(notifications)); + open(server, 1, INVALID); + for (int version = 2; version <= 100; version++) { + change(server, version, version == 100 ? VALID : INVALID); + } + int previous = 0; + while (previous < 100) { + final PublishDiagnosticsParams update = next(notifications); + Assert.assertTrue(update.getVersion() > previous); + previous = update.getVersion(); + if (previous == 100) { + Assert.assertTrue(update.getDiagnostics().isEmpty()); + } + } + server.didClose(new DidCloseTextDocumentParams(new TextDocumentIdentifier(URI))); + Assert.assertNull(next(notifications).getVersion()); + open(server, 1, INVALID); + Assert.assertEquals(Integer.valueOf(1), next(notifications).getVersion()); + } + } + + @Test + public void clientConnectedAfterOpenReceivesCurrentDiagnostics() throws Exception { + final BlockingQueue notifications = new LinkedBlockingQueue<>(); + try (final ImpexLanguageServer server = new ImpexLanguageServer()) { + open(server, 1, INVALID); + server.connect(client(notifications)); + Assert.assertEquals(1, next(notifications).getDiagnostics().size()); + } + } + + @Test + public void negotiatesFlatAndHierarchicalSymbolResponses() throws Exception { + try (final ImpexLanguageServer flat = new ImpexLanguageServer(); + final ImpexLanguageServer hierarchical = new ImpexLanguageServer()) { + flat.initialize(new InitializeParams()).get(); + open(flat, 1, VALID); + Assert.assertTrue(flat.documentSymbol(new DocumentSymbolParams(new TextDocumentIdentifier(URI))) + .get().getFirst().isLeft()); + final DocumentSymbolCapabilities symbols = new DocumentSymbolCapabilities(); + symbols.setHierarchicalDocumentSymbolSupport(true); + final TextDocumentClientCapabilities text = new TextDocumentClientCapabilities(); + text.setDocumentSymbol(symbols); + final ClientCapabilities capabilities = new ClientCapabilities(); + capabilities.setTextDocument(text); + final InitializeParams params = new InitializeParams(); + params.setCapabilities(capabilities); + hierarchical.initialize(params).get(); + open(hierarchical, 1, VALID); + Assert.assertTrue(hierarchical.documentSymbol(new DocumentSymbolParams(new TextDocumentIdentifier(URI))) + .get().getFirst().isRight()); + } + } + + @Test + public void hoverAndSymbolsWorkWithoutACommerceIndexAndDisappearOnClose() throws Exception { + try (final ImpexLanguageServer server = new ImpexLanguageServer()) { + open(server, 1, "$catalog=demo\nINSERT T;a;b\n;id;$catalog"); + Assert.assertTrue(server.hover(new HoverParams(new TextDocumentIdentifier(URI), new Position(2, 6))) + .get(5, TimeUnit.SECONDS).getContents().getRight().getValue().contains("$catalog=demo")); + Assert.assertEquals(2, server.documentSymbol(new DocumentSymbolParams(new TextDocumentIdentifier(URI))) + .get(5, TimeUnit.SECONDS).size()); + server.didClose(new DidCloseTextDocumentParams(new TextDocumentIdentifier(URI))); + Assert.assertNull(server.hover(new HoverParams(new TextDocumentIdentifier(URI), new Position(2, 6))).get()); + Assert.assertTrue(server.documentSymbol(new DocumentSymbolParams(new TextDocumentIdentifier(URI))).get().isEmpty()); + } + } + + private LanguageClient client(final BlockingQueue notifications) { + return (LanguageClient) Proxy.newProxyInstance(LanguageClient.class.getClassLoader(), + new Class[] {LanguageClient.class}, (proxy, method, args) -> { + if ("publishDiagnostics".equals(method.getName())) { + notifications.add((PublishDiagnosticsParams) args[0]); + } + return CompletableFuture.class.isAssignableFrom(method.getReturnType()) + ? CompletableFuture.completedFuture(null) : null; + }); + } + + private PublishDiagnosticsParams next(final BlockingQueue notifications) throws Exception { + final PublishDiagnosticsParams notification = notifications.poll(5, TimeUnit.SECONDS); + Assert.assertNotNull("Expected diagnostics notification", notification); + Assert.assertEquals(URI, notification.getUri()); + return notification; + } + + private void open(final ImpexLanguageServer server, final int version, final String text) { + server.didOpen(new DidOpenTextDocumentParams(new TextDocumentItem(URI, "impex", version, text))); + } + + private void change(final ImpexLanguageServer server, final int version, final String text) { + server.didChange(new DidChangeTextDocumentParams(new VersionedTextDocumentIdentifier(URI, version), + Arrays.asList(new TextDocumentContentChangeEvent(text)))); + } +} diff --git a/com.hybris.hyeclipse.impex.tests/src/com/hybris/hyeclipse/impex/tests/ImpexDocumentAnalysisTest.java b/com.hybris.hyeclipse.impex.tests/src/com/hybris/hyeclipse/impex/tests/ImpexDocumentAnalysisTest.java new file mode 100644 index 00000000..3593e685 --- /dev/null +++ b/com.hybris.hyeclipse.impex.tests/src/com/hybris/hyeclipse/impex/tests/ImpexDocumentAnalysisTest.java @@ -0,0 +1,150 @@ +/******************************************************************************* + * Copyright 2020 SAP + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + ******************************************************************************/ +package com.hybris.hyeclipse.impex.tests; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import org.eclipse.lsp4j.Diagnostic; +import org.eclipse.lsp4j.DiagnosticSeverity; +import org.eclipse.lsp4j.DocumentSymbol; +import org.eclipse.lsp4j.Hover; +import org.eclipse.lsp4j.MarkupKind; +import org.eclipse.lsp4j.Position; +import org.junit.Assert; +import org.junit.Test; + +import com.hybris.hyeclipse.impex.ls.format.TextPositions; +import com.hybris.hyeclipse.impex.ls.types.ImpexDocumentAnalysis; +import com.hybris.hyeclipse.impex.ls.types.ImpexLanguageFeatures; +import com.hybris.hyeclipse.impex.ls.types.TypeCatalog; + +public class ImpexDocumentAnalysisTest { + + @Test + public void hoversTypesInheritedAttributesAndNestedReferences() { + Assert.assertTrue(hover("INSERT Pro|duct;code").getContents().getRight().getValue().contains("demo.ProductModel")); + Assert.assertTrue(hover("INSERT Product;u|id").getContents().getRight().getValue().contains("Product.uid")); + Assert.assertTrue(hover("INSERT Product;catalogVersion(catalog(i|d),version)") + .getContents().getRight().getValue().contains("Catalog.id")); + Assert.assertEquals(new Position(0, 7), hover("INSERT Pro|duct;code").getRange().getStart()); + Assert.assertEquals(new Position(0, 14), hover("INSERT Pro|duct;code").getRange().getEnd()); + } + + @Test + public void macroHoverUsesCurrentDeclarationOrLatestEarlierDefinitionAsPlainText() { + final Hover reference = hover("$catalog=one\n$catalog=\nINSERT Product;code\n;id;$cat|alog"); + Assert.assertEquals(MarkupKind.PLAINTEXT, reference.getContents().getRight().getKind()); + Assert.assertTrue(reference.getContents().getRight().getValue().contains("")); + Assert.assertFalse(reference.getContents().getRight().getValue().contains("$catalog=one")); + Assert.assertTrue(hover("$cat|alog=one").getContents().getRight().getValue().contains("$catalog=one")); + Assert.assertTrue(hover("$catalog=one\n$cat|alog=two").getContents().getRight().getValue().contains("$catalog=two")); + Assert.assertNull(hover("INSERT Product;code\n;id;$cat|alog\n$catalog=later")); + Assert.assertNull(hover("$catalog=$cat|alog")); + } + + @Test + public void hoverDoesNotGuessAndBoundsLongDefinitions() { + for (final String source : new String[] {"INSERT Unk|nown;code", "INSERT Product;missing(na|me)", + "INSERT Product;code\n;id;na|me", "# $cat|alog", "#% $cat|alog"}) { + Assert.assertNull(source, hover(source)); + } + final String definition = "$catalog=" + "x".repeat(5000) + "\nINSERT Product;code\n;id;$cat|alog"; + Assert.assertTrue(hover(definition).getContents().getRight().getValue().length() < 2200); + Assert.assertTrue(hover(definition).getContents().getRight().getValue().contains("truncated")); + } + + @Test + public void symbolsIdentifyMacroAndHeaderDeclarationsInSourceOrder() { + final String source = "$catalog=demo\r\nINSERT_UPDATE Product;code\r\n;id\r\n# comment\r\n" + + "\"$lang=en\"\r\nUPDATE Unknown;name\r\n;id;Name"; + final List symbols = new ImpexDocumentAnalysis().symbols(source, () -> false); + Assert.assertEquals(Arrays.asList("$catalog", "INSERT_UPDATE Product", "$lang", "UPDATE Unknown"), + symbols.stream().map(DocumentSymbol::getName).collect(Collectors.toList())); + Assert.assertEquals(new Position(1, 14), symbols.get(1).getSelectionRange().getStart()); + Assert.assertEquals(new Position(1, 21), symbols.get(1).getSelectionRange().getEnd()); + Assert.assertEquals(new Position(4, 1), symbols.get(2).getSelectionRange().getStart()); + Assert.assertEquals(new Position(4, 6), symbols.get(2).getSelectionRange().getEnd()); + for (final DocumentSymbol symbol : symbols) { + final TextPositions positions = new TextPositions(source); + Assert.assertTrue(positions.offsetAt(symbol.getRange().getStart()) + <= positions.offsetAt(symbol.getSelectionRange().getStart())); + Assert.assertTrue(positions.offsetAt(symbol.getSelectionRange().getEnd()) + <= positions.offsetAt(symbol.getRange().getEnd())); + } + } + + @Test + public void symbolsDoNotRecognizeHeadersInsideQuotedValuesOrInferMacroScope() { + final String source = "$a=one\n$a=two\nINSERT T;a;b\n;id;\"INSERT Other;a;b\ntext\"\nUPDATE T;a;b\n"; + Assert.assertEquals(Arrays.asList("$a", "$a", "INSERT T", "UPDATE T"), + new ImpexDocumentAnalysis().symbols(source, () -> false).stream() + .map(DocumentSymbol::getName).collect(Collectors.toList())); + } + + @Test + public void unclosedQuotesPointToTheOpeningCellNotTheEndOfFile() { + final Diagnostic diagnostic = diagnostics("INSERT T;a;b\r\n;id;\"line1\r\nline2").getFirst(); + Assert.assertEquals("impex.unclosedQuote", diagnostic.getCode().getLeft()); + Assert.assertEquals(DiagnosticSeverity.Error, diagnostic.getSeverity()); + Assert.assertEquals(new Position(1, 4), diagnostic.getRange().getStart()); + Assert.assertEquals(new Position(1, 5), diagnostic.getRange().getEnd()); + } + + @Test + public void textAfterQuotesPointsToTheOffendingCharacterAndDoesNotEscapeBackslashes() { + final Diagnostic plain = diagnostics(";id;\"abc\"def").getFirst(); + Assert.assertEquals("impex.textAfterQuote", plain.getCode().getLeft()); + Assert.assertEquals(new Position(0, 9), plain.getRange().getStart()); + Assert.assertEquals(new Position(0, 10), plain.getRange().getEnd()); + Assert.assertEquals(new Position(0, 9), diagnostics(";id;\"5\\\" monitor\"").getFirst().getRange().getStart()); + } + + @Test + public void quoteDiagnosticsUseUtf16WithoutSplittingSurrogatePairs() { + final Diagnostic diagnostic = diagnostics("# é😀\r\n;id;\"a\"😀").getFirst(); + Assert.assertEquals(new Position(1, 7), diagnostic.getRange().getStart()); + Assert.assertEquals(new Position(1, 9), diagnostic.getRange().getEnd()); + } + + @Test + public void validCsvAndRuntimeDependentConstructsDoNotProduceFalseErrors() { + for (final String source : new String[] { + ";id;abc\"def\n", ";id;\"5\"\" monitor\"\n", ";id;\"multiline\nvalue\"\n", + ";id;\"value\" ;next\n", ";id;value\\\ncontinued\n", "# a comment with a quote \"\n", + "INSERT Unknown;a[unlessExisting=yes];missing\n;id;$unknown;;\n", + "#% if: unknownRuntimeCondition\n;id;value\n#% endif:\n", ";id;unfinished\\"}) { + Assert.assertTrue(source, diagnostics(source).isEmpty()); + } + } + + @Test + public void outputLimitsAndCancellationAreConservative() { + final ImpexDocumentAnalysis analysis = new ImpexDocumentAnalysis(); + Assert.assertEquals(100, diagnostics(";id;\"a\"x\n".repeat(150)).size()); + Assert.assertEquals(1000, analysis.symbols("$a=x\n".repeat(1100), () -> false).size()); + Assert.assertTrue(analysis.symbols("INSERT T;a\n", () -> true).isEmpty()); + Assert.assertTrue(analysis.diagnostics(";id;\"unclosed", () -> true).isEmpty()); + Assert.assertNull(new ImpexLanguageFeatures().hover("INSERT Product;", new Position(0, 9), + TypeCatalog.empty(), () -> true)); + } + + private Hover hover(final String marked) { + final int offset = marked.indexOf('|'); + final String text = marked.replace("|", ""); + return new ImpexLanguageFeatures().hover(text, new TextPositions(text).positionAt(offset), + ImpexCompletionTest.catalog(), () -> false); + } + + private List diagnostics(final String text) { + return new ImpexDocumentAnalysis().diagnostics(text, () -> false); + } +} diff --git a/com.hybris.hyeclipse.impex.tests/src/com/hybris/hyeclipse/impex/tests/ImpexLanguageServerTest.java b/com.hybris.hyeclipse.impex.tests/src/com/hybris/hyeclipse/impex/tests/ImpexLanguageServerTest.java index 6369115e..0e82869a 100644 --- a/com.hybris.hyeclipse.impex.tests/src/com/hybris/hyeclipse/impex/tests/ImpexLanguageServerTest.java +++ b/com.hybris.hyeclipse.impex.tests/src/com/hybris/hyeclipse/impex/tests/ImpexLanguageServerTest.java @@ -13,10 +13,12 @@ import java.util.Arrays; import java.util.ConcurrentModificationException; import java.util.List; +import java.util.concurrent.BlockingQueue; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; +import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import org.eclipse.jface.text.Document; @@ -28,9 +30,12 @@ import org.eclipse.lsp4j.DidOpenTextDocumentParams; import org.eclipse.lsp4j.DocumentFormattingParams; import org.eclipse.lsp4j.DocumentRangeFormattingParams; +import org.eclipse.lsp4j.DocumentSymbolParams; import org.eclipse.lsp4j.FormattingOptions; +import org.eclipse.lsp4j.HoverParams; import org.eclipse.lsp4j.InitializeParams; import org.eclipse.lsp4j.Position; +import org.eclipse.lsp4j.PublishDiagnosticsParams; import org.eclipse.lsp4j.Range; import org.eclipse.lsp4j.ServerCapabilities; import org.eclipse.lsp4j.TextDocumentContentChangeEvent; @@ -108,8 +113,8 @@ public void advertisesOnlyImplementedServices() throws Exception { Assert.assertTrue(capabilities.getDocumentRangeFormattingProvider().getLeft()); Assert.assertNotNull(capabilities.getCompletionProvider()); Assert.assertTrue(capabilities.getDefinitionProvider().getLeft()); - Assert.assertNull(capabilities.getHoverProvider()); - Assert.assertNull(capabilities.getDocumentSymbolProvider()); + Assert.assertTrue(capabilities.getHoverProvider().getLeft()); + Assert.assertTrue(capabilities.getDocumentSymbolProvider().getLeft()); } } @@ -179,13 +184,18 @@ public void exchangesRealJsonRpcMessagesAndCanRestartConnection() throws Excepti Assert.assertEquals(provider.hashCode(), new ImpexConnectionProvider().hashCode()); for (int run = 0; run < 2; run++) { final ExecutorService executor = Executors.newFixedThreadPool(2); + final BlockingQueue diagnostics = new LinkedBlockingQueue<>(); Future listening = null; try { provider.start(); final LanguageClient client = (LanguageClient) Proxy.newProxyInstance(LanguageClient.class.getClassLoader(), - new Class[] {LanguageClient.class}, (proxy, method, args) -> - CompletableFuture.class.isAssignableFrom(method.getReturnType()) - ? CompletableFuture.completedFuture(null) : null); + new Class[] {LanguageClient.class}, (proxy, method, args) -> { + if ("publishDiagnostics".equals(method.getName())) { + diagnostics.add((PublishDiagnosticsParams) args[0]); + } + return CompletableFuture.class.isAssignableFrom(method.getReturnType()) + ? CompletableFuture.completedFuture(null) : null; + }); final Launcher launcher = new Launcher.Builder() .setLocalService(client).setRemoteInterface(LanguageServer.class) .setInput(provider.getInputStream()).setOutput(provider.getOutputStream()) @@ -198,11 +208,27 @@ public void exchangesRealJsonRpcMessagesAndCanRestartConnection() throws Excepti final List edits = remote.getTextDocumentService().formatting(formatting()) .get(5, TimeUnit.SECONDS); Assert.assertEquals(2, edits.size()); + final PublishDiagnosticsParams firstDiagnostics = diagnostics.poll(5, TimeUnit.SECONDS); + Assert.assertNotNull(firstDiagnostics); + Assert.assertEquals(Integer.valueOf(1), firstDiagnostics.getVersion()); + Assert.assertTrue(firstDiagnostics.getDiagnostics().isEmpty()); + Assert.assertEquals("INSERT T", remote.getTextDocumentService().documentSymbol( + new DocumentSymbolParams(new TextDocumentIdentifier(URI))).get(5, TimeUnit.SECONDS) + .getFirst().getLeft().getName()); Assert.assertEquals(4, remote.getTextDocumentService().completion(new CompletionParams( new TextDocumentIdentifier(URI), new Position(0, 0))).get(5, TimeUnit.SECONDS) .getRight().getItems().size()); Assert.assertTrue(remote.getTextDocumentService().definition(new DefinitionParams( new TextDocumentIdentifier(URI), new Position(0, 1))).get(5, TimeUnit.SECONDS).getLeft().isEmpty()); + remote.getTextDocumentService().didChange(new DidChangeTextDocumentParams( + new VersionedTextDocumentIdentifier(URI, 2), Arrays.asList(new TextDocumentContentChangeEvent( + "$catalog=demo\nINSERT T;a;b\n;id;$catalog\n")))); + Assert.assertTrue(remote.getTextDocumentService().hover(new HoverParams(new TextDocumentIdentifier(URI), + new Position(2, 6))).get(5, TimeUnit.SECONDS).getContents().getRight().getValue() + .contains("$catalog=demo")); + final PublishDiagnosticsParams updatedDiagnostics = diagnostics.poll(5, TimeUnit.SECONDS); + Assert.assertNotNull(updatedDiagnostics); + Assert.assertEquals(Integer.valueOf(2), updatedDiagnostics.getVersion()); remote.shutdown().get(5, TimeUnit.SECONDS); remote.exit(); } finally { diff --git a/com.hybris.hyeclipse.impex/README.md b/com.hybris.hyeclipse.impex/README.md index 03529093..eab90945 100644 --- a/com.hybris.hyeclipse.impex/README.md +++ b/com.hybris.hyeclipse.impex/README.md @@ -39,8 +39,13 @@ types. The index is reused and refreshed by the existing background indexing job Quoted/continued headers and macro-expanded header structures are not yet resolved for type assistance. See the [language-service policy](../com.hybris.hyeclipse.impex.ls/README.md). -Macro hover, symbols, diagnostics, and interactive UI/upgrade validation remain -subsequent slices. The legacy editor has not been retired. +Hover now shows generated model/attribute details and the source of macro definitions +without evaluating them. The Outline lists header and macro declarations. Confirmed +CSV quote errors appear as diagnostics and clear after correction or document close. +Unknown types/macros and runtime-dependent import behavior are not reported as errors. + +Interactive UI/upgrade validation, CSV compatibility refinements, and multi-platform +indexing remain outstanding. The legacy editor has not been retired. Run the isolated OSGi tests: @@ -50,7 +55,8 @@ Run the isolated OSGi tests: Rebuild both editor bundles so registration tests do not use cached legacy metadata. The tests exercise the packaged grammar, file creation, registration, formatting, -real JSON-RPC lifecycle, scoped completion/navigation, index refresh, cancellation, -and LSP4E's stale-edit protection and document undo/redo. +real JSON-RPC lifecycle, scoped completion/navigation, hover, symbols, diagnostic +publication/clearing, index refresh, cancellation, and LSP4E's stale-edit protection +and document undo/redo. They do not replace interactive shortcut, wizard, light/dark-theme, and existing-workspace upgrade testing. diff --git a/com.hybris.hyeclipse.impex/src/com/hybris/hyeclipse/impex/lsp/ImpexConnectionProvider.java b/com.hybris.hyeclipse.impex/src/com/hybris/hyeclipse/impex/lsp/ImpexConnectionProvider.java index 933fe7de..b4c71b17 100644 --- a/com.hybris.hyeclipse.impex/src/com/hybris/hyeclipse/impex/lsp/ImpexConnectionProvider.java +++ b/com.hybris.hyeclipse.impex/src/com/hybris/hyeclipse/impex/lsp/ImpexConnectionProvider.java @@ -57,6 +57,7 @@ public synchronized void start() throws IOException { final Launcher launcher = new Launcher.Builder() .setLocalService(server).setRemoteInterface(LanguageClient.class) .setInput(serverInput).setOutput(serverOutput).setExecutorService(transport).create(); + server.connect(launcher.getRemoteProxy()); listening = launcher.startListening(); } catch (final IOException | RuntimeException e) { try { @@ -85,9 +86,6 @@ public InputStream getErrorStream() { @Override public synchronized void stop() { - if (server != null) { - server.close(); - } if (listening != null) { listening.cancel(true); } @@ -105,6 +103,10 @@ public synchronized void stop() { } } } + // Unblock pipe writers before taking the server lock during shutdown. + if (server != null) { + server.close(); + } if (transport != null) { transport.shutdownNow(); } diff --git a/docs/dev/impex/editor-replacement-plan.md b/docs/dev/impex/editor-replacement-plan.md index 788af287..9c418f44 100644 --- a/docs/dev/impex/editor-replacement-plan.md +++ b/docs/dev/impex/editor-replacement-plan.md @@ -53,7 +53,14 @@ Status: migration started on `feature/impex-lsp-migration`; legacy editor retain including 65 ImpEx tests. The p2 ZIP contains the language features, scoped workspace adapter, and localized proposal descriptions. Live content-assist, hyperlink, and multi-platform workflow checks remain outstanding. -- Next: macro hover, symbols/diagnostics, and interactive UI/upgrade checks. TextMate continuation +- Added plain-text type/attribute/macro hover, lexical header/macro document symbols, + and pushed diagnostics for confirmed CSV quote errors. Diagnostics coalesce edits, + publish only current snapshots, and clear on correction/close; no runtime or + unknown-name validation is inferred. Symbol response shape follows client capabilities. +- Verification: all 171 tests passed in the full reactor, including 80 ImpEx tests. + Tests cover hover/outline ranges, quote origins, surrogate pairs, notification + lifecycle, rapid edits/reopening, and real JSON-RPC hover/symbol/diagnostic exchange. +- Next: interactive UI/upgrade checks and CSV/header compatibility refinements. TextMate continuation highlighting still needs refinement. The legacy editor must not be retired yet. ## Goal and scope From da8d4366193db561f5fb6d978507eb83b534175b Mon Sep 17 00:00:00 2001 From: Pawel Wolanski Date: Mon, 23 Nov 2026 01:47:38 +0100 Subject: [PATCH 07/25] refactor(impex)!: remove legacy editor Make the Generic Editor/LSP implementation the default for .impex. Preserve wizard command IDs and historical update-site snapshots. BREAKING CHANGE: remove com.hybris.hyeclipse.impexed and its editor ID. Existing installations may need reassociation or manual uninstallation; integrations requiring the removed bundle must migrate. --- CHANGELOG.md | 6 + README.md | 2 +- REUSE.toml | 2 +- com.hybris.hyeclipse.feature/feature.xml | 7 - .../META-INF/MANIFEST.MF | 3 +- .../impex/tests/ImpexRegistrationTest.java | 23 +- com.hybris.hyeclipse.impex/README.md | 31 +- com.hybris.hyeclipse.impex/plugin.properties | 4 +- com.hybris.hyeclipse.impex/plugin.xml | 3 +- com.hybris.hyeclipse.impexed/.classpath | 7 - com.hybris.hyeclipse.impexed/.gitignore | 2 - com.hybris.hyeclipse.impexed/.options | 2 - com.hybris.hyeclipse.impexed/.project | 44 -- .../org.eclipse.core.resources.prefs | 2 - .../.settings/org.eclipse.m2e.core.prefs | 4 - .../META-INF/MANIFEST.MF | 33 -- com.hybris.hyeclipse.impexed/build.properties | 7 - com.hybris.hyeclipse.impexed/icon/hybris.ico | Bin 1150 -> 0 bytes .../plugin.properties | 1 - com.hybris.hyeclipse.impexed/plugin.xml | 88 ---- com.hybris.hyeclipse.impexed/pom.xml | 18 - .../.fbprefs | 127 ------ .../project-settings/PMD_ruleset.xml | 248 ------------ .../project-settings/checkstylerules.xml | 107 ----- .../project-settings/code cleanup.xml | 56 --- .../project-settings/code formatter.xml | 283 ------------- .../com/hybris/impexformatter/Activator.java | 92 ----- .../impexformatter/DocumentProvider.java | 51 --- .../ImpexDocumentPartitioner.java | 186 --------- .../impexformatter/actions/CommentAction.java | 36 -- .../impexformatter/actions/Formatter.java | 221 ---------- .../impexformatter/actions/LineData.java | 99 ----- .../ImpexCommandContentAssistProcessor.java | 237 ----------- .../ImpexCommentContentAssistProcessor.java | 71 ---- .../ImpexDataContentAssistProcessor.java | 72 ---- ...mpexInstructionContentAssistProcessor.java | 142 ------- ...exTypeAttributeContentAssistProcessor.java | 377 ------------------ ...ImpexTypeSystemContentAssistProcessor.java | 367 ----------------- .../impexformatter/editors/ColorProvider.java | 108 ----- .../impexformatter/editors/ImpexEditor.java | 51 --- .../editors/ImpexFormatAction.java | 49 --- .../editors/ImpexPageEditor.java | 183 --------- .../editors/ImpexSourceViewerConfig.java | 150 ------- .../editors/MultiPageEditorContributor.java | 104 ----- .../handlers/NewImpexWizardHandler.java | 43 -- .../hyperlink/ImpexTypeHyperlink.java | 84 ---- .../hyperlink/ImpexTypeHyperlinkDetector.java | 84 ---- .../preferences/ImpexPreferencePage.java | 75 ---- .../preferences/PreferenceConstants.java | 33 -- .../preferences/PreferenceInitializer.java | 49 --- .../impexformatter/rules/RuleFactory.java | 79 ---- .../scanners/ImpexBracesAutoEditStrategy.java | 54 --- .../scanners/ImpexPartitionScanner.java | 60 --- .../scanners/ImpexRuleScanner.java | 101 ----- .../scanners/InstructionsRuleScanner.java | 75 ---- .../impexformatter/utils/ColorHelper.java | 32 -- .../impexformatter/utils/StringHelper.java | 18 - .../wizards/NewImpexWizard.java | 166 -------- .../wizards/NewImpexWizardPage.java | 191 --------- com.hybris.hyeclipse.impexed/test.impex | 207 ---------- docs/dev/impex/editor-replacement-plan.md | 54 ++- docs/internal/type-system-repository.md | 5 +- pom.xml | 1 - 63 files changed, 86 insertions(+), 5031 deletions(-) delete mode 100644 com.hybris.hyeclipse.impexed/.classpath delete mode 100644 com.hybris.hyeclipse.impexed/.gitignore delete mode 100644 com.hybris.hyeclipse.impexed/.options delete mode 100644 com.hybris.hyeclipse.impexed/.project delete mode 100644 com.hybris.hyeclipse.impexed/.settings/org.eclipse.core.resources.prefs delete mode 100644 com.hybris.hyeclipse.impexed/.settings/org.eclipse.m2e.core.prefs delete mode 100755 com.hybris.hyeclipse.impexed/META-INF/MANIFEST.MF delete mode 100755 com.hybris.hyeclipse.impexed/build.properties delete mode 100644 com.hybris.hyeclipse.impexed/icon/hybris.ico delete mode 100644 com.hybris.hyeclipse.impexed/plugin.properties delete mode 100755 com.hybris.hyeclipse.impexed/plugin.xml delete mode 100755 com.hybris.hyeclipse.impexed/pom.xml delete mode 100755 com.hybris.hyeclipse.impexed/project-settings/.metadata/.plugins/edu.umd.cs.findbugs.plugin.eclipse/.fbprefs delete mode 100755 com.hybris.hyeclipse.impexed/project-settings/PMD_ruleset.xml delete mode 100755 com.hybris.hyeclipse.impexed/project-settings/checkstylerules.xml delete mode 100755 com.hybris.hyeclipse.impexed/project-settings/code cleanup.xml delete mode 100755 com.hybris.hyeclipse.impexed/project-settings/code formatter.xml delete mode 100755 com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/Activator.java delete mode 100755 com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/DocumentProvider.java delete mode 100644 com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/ImpexDocumentPartitioner.java delete mode 100755 com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/actions/CommentAction.java delete mode 100755 com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/actions/Formatter.java delete mode 100755 com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/actions/LineData.java delete mode 100755 com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/assistprocessors/ImpexCommandContentAssistProcessor.java delete mode 100644 com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/assistprocessors/ImpexCommentContentAssistProcessor.java delete mode 100644 com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/assistprocessors/ImpexDataContentAssistProcessor.java delete mode 100755 com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/assistprocessors/ImpexInstructionContentAssistProcessor.java delete mode 100644 com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/assistprocessors/ImpexTypeAttributeContentAssistProcessor.java delete mode 100644 com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/assistprocessors/ImpexTypeSystemContentAssistProcessor.java delete mode 100755 com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/editors/ColorProvider.java delete mode 100755 com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/editors/ImpexEditor.java delete mode 100755 com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/editors/ImpexFormatAction.java delete mode 100755 com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/editors/ImpexPageEditor.java delete mode 100755 com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/editors/ImpexSourceViewerConfig.java delete mode 100755 com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/editors/MultiPageEditorContributor.java delete mode 100644 com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/handlers/NewImpexWizardHandler.java delete mode 100644 com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/hyperlink/ImpexTypeHyperlink.java delete mode 100644 com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/hyperlink/ImpexTypeHyperlinkDetector.java delete mode 100755 com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/preferences/ImpexPreferencePage.java delete mode 100755 com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/preferences/PreferenceConstants.java delete mode 100755 com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/preferences/PreferenceInitializer.java delete mode 100755 com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/rules/RuleFactory.java delete mode 100755 com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/scanners/ImpexBracesAutoEditStrategy.java delete mode 100755 com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/scanners/ImpexPartitionScanner.java delete mode 100755 com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/scanners/ImpexRuleScanner.java delete mode 100755 com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/scanners/InstructionsRuleScanner.java delete mode 100755 com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/utils/ColorHelper.java delete mode 100644 com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/utils/StringHelper.java delete mode 100755 com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/wizards/NewImpexWizard.java delete mode 100755 com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/wizards/NewImpexWizardPage.java delete mode 100755 com.hybris.hyeclipse.impexed/test.impex diff --git a/CHANGELOG.md b/CHANGELOG.md index 81880be4..a10a6e73 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,11 @@ # Changelog +## Unreleased + +- Replace the legacy ImpEx editor bundle with Generic Editor/TM4E/LSP4E language support. +- Make **ImpEx Editor** the default for `.impex` files; preserve the existing new-file wizard command and shortcut. +- Existing workspaces may need to reselect the editor and uninstall any independently installed legacy bundle. + ## v22.11.0 (18/11/2026) - Modernize Java 21 source code and update build tooling. diff --git a/README.md b/README.md index 9299c103..57c3c812 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,7 @@ Features * Configure the runtime JVM with optimal settings to run JUnit tests * Add the JDBC driver to the classpath (required to be able to run JUnit tests) * Actions to build the platform, ensuring projects are refreshed after the platform has generated files -* Impex editor with type ahead and formatting functionality +* ImpEx language editor with TextMate highlighting, LSP completion/navigation, and safe formatting * Create working sets from localextensions.xml * Disable unnecessary extension modules * Build individual extensions diff --git a/REUSE.toml b/REUSE.toml index ab2f28d4..d5619216 100644 --- a/REUSE.toml +++ b/REUSE.toml @@ -53,7 +53,7 @@ SPDX-FileCopyrightText = "2006 SAP SE or an SAP affiliate company and *Eclipse P SPDX-License-Identifier = "Apache-2.0" [[annotations]] -path = "com.hybris.hyeclipse.impexed/**" +path = ["com.hybris.hyeclipse.impex/**", "com.hybris.hyeclipse.impex.ls/**", "com.hybris.hyeclipse.impex.tests/**"] precedence = "aggregate" SPDX-FileCopyrightText = "2006 SAP SE or an SAP affiliate company and *Eclipse Plugin for SAP Commerce* contributors" SPDX-License-Identifier = "Apache-2.0" diff --git a/com.hybris.hyeclipse.feature/feature.xml b/com.hybris.hyeclipse.feature/feature.xml index 45522dc1..f6fdb720 100755 --- a/com.hybris.hyeclipse.feature/feature.xml +++ b/com.hybris.hyeclipse.feature/feature.xml @@ -121,13 +121,6 @@ All rights reserved. version="0.0.0" unpack="false"/> - - ImpEx Editor (Preview)** -on an `.impex` file. The preview is not registered as the default editor and does -not claim `.csv` files. Colors follow the installed TM4E theme. +After installing the rebuilt feature, **ImpEx Editor** is the default for `.impex` +files. It does not claim `.csv` files. Colors follow the installed TM4E theme. The canonical grammar is `syntaxes/impex.tmLanguage.json`. Headers, modifiers, macros, data-cell strings, comments, and script directives have initial scopes; @@ -15,7 +15,7 @@ header replacements still require further work. Use **File > New > Other > SAP > New ImpEx File**, or **M1+Shift+Y**, to create files with the replacement wizard. It uses the selected workspace project/folder, refuses overwrites (including local files not yet refreshed into the workspace), -and opens the file in the preview. New files use UTF-8 and the project's configured +and opens the file in the editor. New files use UTF-8 and the project's configured line delimiter. Explicit `.csv` names are accepted but currently open without ImpEx highlighting. The old wizard/command registrations have been transferred to this bundle without changing their IDs or duplicating the shortcut. @@ -25,7 +25,7 @@ The in-process language server now provides safe document/range formatting throu block, or use the caret with no selection for document formatting. Multiline, continued, malformed, or unsupported blocks are left unchanged. See the [formatting policy](../com.hybris.hyeclipse.impex.ls/README.md) for limits and options. -The legacy formatter shortcut is scoped to its own editor to avoid interference. +Formatting uses LSP4E's action; the legacy formatter and its shortcut contribution are removed. Content assist (**Ctrl+Space**) now offers operation/type names, inherited attributes, nested reference attributes, header/column modifiers, supported modifier @@ -45,15 +45,24 @@ CSV quote errors appear as diagnostics and clear after correction or document cl Unknown types/macros and runtime-dependent import behavior are not reported as errors. Interactive UI/upgrade validation, CSV compatibility refinements, and multi-platform -indexing remain outstanding. The legacy editor has not been retired. +indexing remain outstanding; removal approval does not imply those checks were performed. + +## Existing installations + +- User-specific file associations can override the new default. Reselect + **Open With > ImpEx Editor** or update the `.impex` association in Eclipse preferences. +- An independently installed `com.hybris.hyeclipse.impexed` bundle may remain after + a feature upgrade. Review **Help > About Eclipse > Installation Details** and + uninstall the old editor if still present. No workspace preferences are reset automatically. +- Historical published update-site snapshots are unchanged; new builds exclude the old bundle. Run the isolated OSGi tests: ```bash -./mvnw -pl com.hybris.hyeclipse.commons,com.hybris.hyeclipse.impexed,com.hybris.hyeclipse.impex.ls,com.hybris.hyeclipse.impex,com.hybris.hyeclipse.impex.tests -am verify +./mvnw -pl com.hybris.hyeclipse.commons,com.hybris.hyeclipse.impex.ls,com.hybris.hyeclipse.impex,com.hybris.hyeclipse.impex.tests -am verify ``` -Rebuild both editor bundles so registration tests do not use cached legacy metadata. +The tests assert the new default registration and absence of legacy runtime contributions. The tests exercise the packaged grammar, file creation, registration, formatting, real JSON-RPC lifecycle, scoped completion/navigation, hover, symbols, diagnostic publication/clearing, index refresh, cancellation, and LSP4E's stale-edit protection diff --git a/com.hybris.hyeclipse.impex/plugin.properties b/com.hybris.hyeclipse.impex/plugin.properties index f9651705..d2ad3bbd 100644 --- a/com.hybris.hyeclipse.impex/plugin.properties +++ b/com.hybris.hyeclipse.impex/plugin.properties @@ -1,8 +1,8 @@ bundleName=SAP Commerce Cloud - ImpEx language support contentTypeName=ImpEx -editorName=ImpEx Editor (Preview) +editorName=ImpEx Editor wizardName=New ImpEx File -wizardDescription=Create an ImpEx file and open it in the ImpEx editor preview. +wizardDescription=Create an ImpEx file and open it in the ImpEx editor. sapCategoryName=SAP commandCategoryName=ImpEx languageServerName=ImpEx language server diff --git a/com.hybris.hyeclipse.impex/plugin.xml b/com.hybris.hyeclipse.impex/plugin.xml index 4f44ad2a..e11822ef 100644 --- a/com.hybris.hyeclipse.impex/plugin.xml +++ b/com.hybris.hyeclipse.impex/plugin.xml @@ -7,7 +7,7 @@ + class="org.eclipse.ui.internal.genericeditor.ExtensionBasedTextEditor" extensions="impex" default="true"> @@ -21,6 +21,7 @@ contentType="com.hybris.hyeclipse.impex.impex"/> + diff --git a/com.hybris.hyeclipse.impexed/.classpath b/com.hybris.hyeclipse.impexed/.classpath deleted file mode 100644 index 2d6b678d..00000000 --- a/com.hybris.hyeclipse.impexed/.classpath +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/com.hybris.hyeclipse.impexed/.gitignore b/com.hybris.hyeclipse.impexed/.gitignore deleted file mode 100644 index a44d20e9..00000000 --- a/com.hybris.hyeclipse.impexed/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -.DS_Store -/target/ diff --git a/com.hybris.hyeclipse.impexed/.options b/com.hybris.hyeclipse.impexed/.options deleted file mode 100644 index d7f099f6..00000000 --- a/com.hybris.hyeclipse.impexed/.options +++ /dev/null @@ -1,2 +0,0 @@ -#Turn on debugging here -com.hybris.hyeclipse.impexed/debug=true \ No newline at end of file diff --git a/com.hybris.hyeclipse.impexed/.project b/com.hybris.hyeclipse.impexed/.project deleted file mode 100644 index 1670dad2..00000000 --- a/com.hybris.hyeclipse.impexed/.project +++ /dev/null @@ -1,44 +0,0 @@ - - - com.hybris.hyeclipse.impexed - - - - - - org.eclipse.ajdt.core.ajbuilder - - - - - org.eclipse.pde.ManifestBuilder - - - - - org.eclipse.pde.SchemaBuilder - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - org.eclipse.pde.PluginNature - - - - 1664951881402 - - 30 - - org.eclipse.core.resources.regexFilterMatcher - node_modules|\.git|__CREATED_BY_JAVA_LANGUAGE_SERVER__ - - - - diff --git a/com.hybris.hyeclipse.impexed/.settings/org.eclipse.core.resources.prefs b/com.hybris.hyeclipse.impexed/.settings/org.eclipse.core.resources.prefs deleted file mode 100644 index 99f26c02..00000000 --- a/com.hybris.hyeclipse.impexed/.settings/org.eclipse.core.resources.prefs +++ /dev/null @@ -1,2 +0,0 @@ -eclipse.preferences.version=1 -encoding/=UTF-8 diff --git a/com.hybris.hyeclipse.impexed/.settings/org.eclipse.m2e.core.prefs b/com.hybris.hyeclipse.impexed/.settings/org.eclipse.m2e.core.prefs deleted file mode 100644 index f897a7f1..00000000 --- a/com.hybris.hyeclipse.impexed/.settings/org.eclipse.m2e.core.prefs +++ /dev/null @@ -1,4 +0,0 @@ -activeProfiles= -eclipse.preferences.version=1 -resolveWorkspaceProjects=true -version=1 diff --git a/com.hybris.hyeclipse.impexed/META-INF/MANIFEST.MF b/com.hybris.hyeclipse.impexed/META-INF/MANIFEST.MF deleted file mode 100755 index 9f3a0cc4..00000000 --- a/com.hybris.hyeclipse.impexed/META-INF/MANIFEST.MF +++ /dev/null @@ -1,33 +0,0 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 2 -Bundle-Name: ImpexFormatter -Bundle-SymbolicName: com.hybris.hyeclipse.impexed;singleton:=true -Bundle-Version: 22.11.1.qualifier -Require-Bundle: org.eclipse.jface.text, - org.eclipse.core.resources, - org.eclipse.ui, - org.eclipse.ui.editors, - org.eclipse.ui.ide, - org.eclipse.core.runtime, - com.google.guava, - org.junit;bundle-version="4.0.0", - com.hybris.hyeclipse.commons -Bundle-RequiredExecutionEnvironment: JavaSE-21 -Import-Package: org.eclipse.jdt.core, - org.eclipse.jdt.internal.ui.text -Bundle-Activator: com.hybris.impexformatter.Activator -Bundle-ActivationPolicy: lazy -Bundle-ClassPath: . -Bundle-Vendor: SAP -Automatic-Module-Name: com.hybris.hyeclipse.impexed -Export-Package: com.hybris.impexformatter, - com.hybris.impexformatter.actions, - com.hybris.impexformatter.assistprocessors, - com.hybris.impexformatter.editors, - com.hybris.impexformatter.handlers, - com.hybris.impexformatter.hyperlink, - com.hybris.impexformatter.preferences, - com.hybris.impexformatter.rules, - com.hybris.impexformatter.scanners, - com.hybris.impexformatter.utils, - com.hybris.impexformatter.wizards diff --git a/com.hybris.hyeclipse.impexed/build.properties b/com.hybris.hyeclipse.impexed/build.properties deleted file mode 100755 index 962d8a96..00000000 --- a/com.hybris.hyeclipse.impexed/build.properties +++ /dev/null @@ -1,7 +0,0 @@ -source.. = src/ -bin.includes = plugin.xml,\ - plugin.properties,\ - META-INF/,\ - .,\ - icon/,\ - .options diff --git a/com.hybris.hyeclipse.impexed/icon/hybris.ico b/com.hybris.hyeclipse.impexed/icon/hybris.ico deleted file mode 100644 index ac20476a5ac15967fb5349e36533a18ee16b7566..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1150 zcmb_b!A-+J5Zp-o^09=-dm}zPO$Vn`kP`CDGbNl9gm@rPf*U}h1d9(TBn6}dXXd;c ztqlf&IBT-&*_qw5&k>p7sw%;+%JxcRAtHAGC@?*bP}cQag!u3Ey1J=>6VMs5&%k{S zJTB5{xAPO-siWm>r~(OJq}0Jk6YEprRoFle6RWh - - - - - - - > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/com.hybris.hyeclipse.impexed/pom.xml b/com.hybris.hyeclipse.impexed/pom.xml deleted file mode 100755 index bf5e471a..00000000 --- a/com.hybris.hyeclipse.impexed/pom.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - 4.0.0 - - - com.hybris.hyeclipse - com.hybris.hyeclipse.parent - 22.11.1-SNAPSHOT - - - com.hybris.hyeclipse.impexed - eclipse-plugin - SAP Commerce Cloud - Eclipse plugin impexed - Impex Editor - - diff --git a/com.hybris.hyeclipse.impexed/project-settings/.metadata/.plugins/edu.umd.cs.findbugs.plugin.eclipse/.fbprefs b/com.hybris.hyeclipse.impexed/project-settings/.metadata/.plugins/edu.umd.cs.findbugs.plugin.eclipse/.fbprefs deleted file mode 100755 index aa3db4fb..00000000 --- a/com.hybris.hyeclipse.impexed/project-settings/.metadata/.plugins/edu.umd.cs.findbugs.plugin.eclipse/.fbprefs +++ /dev/null @@ -1,127 +0,0 @@ -#FindBugs User Preferences -#Mon Sep 12 12:43:03 CEST 2011 -detectorAppendingToAnObjectOutputStream=AppendingToAnObjectOutputStream|true -detectorBadAppletConstructor=BadAppletConstructor|true -detectorBadResultSetAccess=BadResultSetAccess|true -detectorBadSyntaxForRegularExpression=BadSyntaxForRegularExpression|true -detectorBadUseOfReturnValue=BadUseOfReturnValue|true -detectorBadlyOverriddenAdapter=BadlyOverriddenAdapter|true -detectorBooleanReturnNull=BooleanReturnNull|true -detectorCallToUnsupportedMethod=CallToUnsupportedMethod|true -detectorCheckImmutableAnnotation=CheckImmutableAnnotation|true -detectorCheckTypeQualifiers=CheckTypeQualifiers|true -detectorCloneIdiom=CloneIdiom|true -detectorComparatorIdiom=ComparatorIdiom|true -detectorConfusedInheritance=ConfusedInheritance|true -detectorConfusionBetweenInheritedAndOuterMethod=ConfusionBetweenInheritedAndOuterMethod|true -detectorCrossSiteScripting=CrossSiteScripting|true -detectorDoInsideDoPrivileged=DoInsideDoPrivileged|true -detectorDontCatchIllegalMonitorStateException=DontCatchIllegalMonitorStateException|true -detectorDontIgnoreResultOfPutIfAbsent=DontIgnoreResultOfPutIfAbsent|true -detectorDontUseEnum=DontUseEnum|true -detectorDroppedException=DroppedException|true -detectorDumbMethodInvocations=DumbMethodInvocations|true -detectorDumbMethods=DumbMethods|true -detectorDuplicateBranches=DuplicateBranches|true -detectorEmptyZipFileEntry=EmptyZipFileEntry|true -detectorEqualsOperandShouldHaveClassCompatibleWithThis=EqualsOperandShouldHaveClassCompatibleWithThis|true -detectorFinalizerNullsFields=FinalizerNullsFields|true -detectorFindBadCast2=FindBadCast2|true -detectorFindBadForLoop=FindBadForLoop|true -detectorFindCircularDependencies=FindCircularDependencies|false -detectorFindDeadLocalStores=FindDeadLocalStores|true -detectorFindDoubleCheck=FindDoubleCheck|true -detectorFindEmptySynchronizedBlock=FindEmptySynchronizedBlock|true -detectorFindFieldSelfAssignment=FindFieldSelfAssignment|true -detectorFindFinalizeInvocations=FindFinalizeInvocations|true -detectorFindFloatEquality=FindFloatEquality|true -detectorFindHEmismatch=FindHEmismatch|true -detectorFindInconsistentSync2=FindInconsistentSync2|true -detectorFindJSR166LockMonitorenter=FindJSR166LockMonitorenter|true -detectorFindLocalSelfAssignment2=FindLocalSelfAssignment2|true -detectorFindMaskedFields=FindMaskedFields|true -detectorFindMismatchedWaitOrNotify=FindMismatchedWaitOrNotify|true -detectorFindNakedNotify=FindNakedNotify|true -detectorFindNonSerializableStoreIntoSession=FindNonSerializableStoreIntoSession|true -detectorFindNonSerializableValuePassedToWriteObject=FindNonSerializableValuePassedToWriteObject|true -detectorFindNonShortCircuit=FindNonShortCircuit|true -detectorFindNullDeref=FindNullDeref|true -detectorFindNullDerefsInvolvingNonShortCircuitEvaluation=FindNullDerefsInvolvingNonShortCircuitEvaluation|true -detectorFindOpenStream=FindOpenStream|true -detectorFindPuzzlers=FindPuzzlers|true -detectorFindRefComparison=FindRefComparison|true -detectorFindReturnRef=FindReturnRef|true -detectorFindRunInvocations=FindRunInvocations|true -detectorFindSelfComparison=FindSelfComparison|true -detectorFindSelfComparison2=FindSelfComparison2|true -detectorFindSleepWithLockHeld=FindSleepWithLockHeld|true -detectorFindSpinLoop=FindSpinLoop|true -detectorFindSqlInjection=FindSqlInjection|true -detectorFindTwoLockWait=FindTwoLockWait|true -detectorFindUncalledPrivateMethods=FindUncalledPrivateMethods|true -detectorFindUnconditionalWait=FindUnconditionalWait|true -detectorFindUninitializedGet=FindUninitializedGet|true -detectorFindUnrelatedTypesInGenericContainer=FindUnrelatedTypesInGenericContainer|true -detectorFindUnreleasedLock=FindUnreleasedLock|true -detectorFindUnsatisfiedObligation=FindUnsatisfiedObligation|true -detectorFindUnsyncGet=FindUnsyncGet|true -detectorFindUselessControlFlow=FindUselessControlFlow|true -detectorFormatStringChecker=FormatStringChecker|true -detectorHugeSharedStringConstants=HugeSharedStringConstants|true -detectorIDivResultCastToDouble=IDivResultCastToDouble|true -detectorIncompatMask=IncompatMask|true -detectorInconsistentAnnotations=InconsistentAnnotations|true -detectorInefficientMemberAccess=InefficientMemberAccess|true -detectorInefficientToArray=InefficientToArray|true -detectorInfiniteLoop=InfiniteLoop|true -detectorInfiniteRecursiveLoop=InfiniteRecursiveLoop|true -detectorInfiniteRecursiveLoop2=InfiniteRecursiveLoop2|false -detectorInheritanceUnsafeGetResource=InheritanceUnsafeGetResource|true -detectorInitializationChain=InitializationChain|true -detectorInstantiateStaticClass=InstantiateStaticClass|true -detectorInvalidJUnitTest=InvalidJUnitTest|true -detectorIteratorIdioms=IteratorIdioms|true -detectorLazyInit=LazyInit|true -detectorLoadOfKnownNullValue=LoadOfKnownNullValue|true -detectorLostLoggerDueToWeakReference=LostLoggerDueToWeakReference|true -detectorMethodReturnCheck=MethodReturnCheck|true -detectorMultithreadedInstanceAccess=MultithreadedInstanceAccess|true -detectorMutableLock=MutableLock|true -detectorMutableStaticFields=MutableStaticFields|true -detectorNaming=Naming|true -detectorNumberConstructor=NumberConstructor|true -detectorOverridingEqualsNotSymmetrical=OverridingEqualsNotSymmetrical|true -detectorPreferZeroLengthArrays=PreferZeroLengthArrays|true -detectorPublicSemaphores=PublicSemaphores|true -detectorQuestionableBooleanAssignment=QuestionableBooleanAssignment|true -detectorReadOfInstanceFieldInMethodInvokedByConstructorInSuperclass=ReadOfInstanceFieldInMethodInvokedByConstructorInSuperclass|true -detectorReadReturnShouldBeChecked=ReadReturnShouldBeChecked|true -detectorRedundantInterfaces=RedundantInterfaces|true -detectorRepeatedConditionals=RepeatedConditionals|true -detectorRuntimeExceptionCapture=RuntimeExceptionCapture|true -detectorSerializableIdiom=SerializableIdiom|true -detectorStartInConstructor=StartInConstructor|true -detectorStaticCalendarDetector=StaticCalendarDetector|true -detectorStringConcatenation=StringConcatenation|true -detectorSuperfluousInstanceOf=SuperfluousInstanceOf|true -detectorSuspiciousThreadInterrupted=SuspiciousThreadInterrupted|true -detectorSwitchFallthrough=SwitchFallthrough|true -detectorSynchronizeAndNullCheckField=SynchronizeAndNullCheckField|true -detectorSynchronizeOnClassLiteralNotGetClass=SynchronizeOnClassLiteralNotGetClass|true -detectorSynchronizingOnContentsOfFieldToProtectField=SynchronizingOnContentsOfFieldToProtectField|true -detectorURLProblems=URLProblems|true -detectorUncallableMethodOfAnonymousClass=UncallableMethodOfAnonymousClass|true -detectorUnnecessaryMath=UnnecessaryMath|true -detectorUnreadFields=UnreadFields|true -detectorUseObjectEquals=UseObjectEquals|true -detectorUselessSubclassMethod=UselessSubclassMethod|true -detectorVarArgsProblems=VarArgsProblems|true -detectorVolatileUsage=VolatileUsage|true -detectorWaitInLoop=WaitInLoop|true -detectorWrongMapIterator=WrongMapIterator|true -detectorXMLFactoryBypass=XMLFactoryBypass|false -detector_threshold=2 -effort=default -filter_settings=Medium|BAD_PRACTICE,CORRECTNESS,MT_CORRECTNESS,PERFORMANCE,STYLE|false -filter_settings_neg=MALICIOUS_CODE,NOISE,I18N,SECURITY,EXPERIMENTAL| -run_at_full_build=false diff --git a/com.hybris.hyeclipse.impexed/project-settings/PMD_ruleset.xml b/com.hybris.hyeclipse.impexed/project-settings/PMD_ruleset.xml deleted file mode 100755 index 5a806b3e..00000000 --- a/com.hybris.hyeclipse.impexed/project-settings/PMD_ruleset.xml +++ /dev/null @@ -1,248 +0,0 @@ - - - Project Delivery - PMD rule set - .*/Generated/.* - .*/gensrc/.* - .*/jsp/.* - .*_jsp.java - .*/de/hybris/platform/cockpit/services/config/jaxb/.* - .*/virtualjdbc/vjdbc/.* - .*/jax-doclets/.* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/com.hybris.hyeclipse.impexed/project-settings/checkstylerules.xml b/com.hybris.hyeclipse.impexed/project-settings/checkstylerules.xml deleted file mode 100755 index 387fabde..00000000 --- a/com.hybris.hyeclipse.impexed/project-settings/checkstylerules.xml +++ /dev/null @@ -1,107 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/com.hybris.hyeclipse.impexed/project-settings/code cleanup.xml b/com.hybris.hyeclipse.impexed/project-settings/code cleanup.xml deleted file mode 100755 index a723dc68..00000000 --- a/com.hybris.hyeclipse.impexed/project-settings/code cleanup.xml +++ /dev/null @@ -1,56 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/com.hybris.hyeclipse.impexed/project-settings/code formatter.xml b/com.hybris.hyeclipse.impexed/project-settings/code formatter.xml deleted file mode 100755 index d5403a96..00000000 --- a/com.hybris.hyeclipse.impexed/project-settings/code formatter.xml +++ /dev/null @@ -1,283 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/Activator.java b/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/Activator.java deleted file mode 100755 index 76a6e2b8..00000000 --- a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/Activator.java +++ /dev/null @@ -1,92 +0,0 @@ -/******************************************************************************* - * Copyright 2020 SAP - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy - * of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - ******************************************************************************/ -package com.hybris.impexformatter; - -import java.util.List; - -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Status; -import org.eclipse.ui.plugin.AbstractUIPlugin; - -import com.hybris.hyeclipse.commons.typesystem.TypeSystemSnapshot; -import com.hybris.hyeclipse.commons.typesystem.YAttributeDescriptor; - -public class Activator extends AbstractUIPlugin { - - // The plug-in ID - public static final String PLUGIN_ID = "com.hybris.hyeclipse.impexed"; //$NON-NLS-1$ - - public static final String IMPEX_PARTITIONING = "__impex_partitioning"; - public static final String EDITOR_CONTEXT_ID = PLUGIN_ID + ".editorContext"; //$NON-NLS-1$ - - // The shared instance - private static Activator plugin; - - public Activator() { - super(); - if (plugin == null) { - plugin = this; // NOSONAR - } - } - - /** - * Returns the shared instance - * - * @return the shared instance - */ - public static Activator getDefault() { - return plugin; - } - - /** @return current shared generated-model snapshot */ - public TypeSystemSnapshot getTypeSystemSnapshot() { - return com.hybris.hyeclipse.commons.Activator.getDefault().getTypeSystemIndex().getSnapshot(); - } - - public List getAllTypeNames() { - - return getTypeSystemSnapshot().getAllTypeNames(); - } - - public List getAllAttributeNames(String typeName) { - return getTypeSystemSnapshot().getAllAttributeNames(typeName); - } - - public String getAttributeName(String typeName, String qualifier) { - final YAttributeDescriptor attribute = getTypeSystemSnapshot().getAttribute(typeName, qualifier); - return attribute != null ? attribute.getQualifier() : null; - } - - public static void log(String msg) { - getDefault().log(msg, null); - } - - public static void logError(String msg, Exception e) { - getDefault().log(msg, e); - } - - public void log(String msg, Exception e) { - Status status = null; - if (e != null) { - status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, IStatus.ERROR, msg, e); - } - else { - status = new Status(IStatus.INFO, Activator.PLUGIN_ID, IStatus.OK, msg, e); - } - getLog().log(status); - } - -} diff --git a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/DocumentProvider.java b/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/DocumentProvider.java deleted file mode 100755 index 7a20c02e..00000000 --- a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/DocumentProvider.java +++ /dev/null @@ -1,51 +0,0 @@ -/******************************************************************************* - * Copyright 2020 SAP - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy - * of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - ******************************************************************************/ -package com.hybris.impexformatter; - -import org.eclipse.core.runtime.CoreException; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IDocumentExtension3; -import org.eclipse.jface.text.IDocumentPartitioner; -//import org.eclipse.jface.text.rules.FastPartitioner; -import org.eclipse.ui.editors.text.FileDocumentProvider; - -//import com.hybris.impexformatter.scanners.ImpexPartitionScanner; - -public class DocumentProvider extends FileDocumentProvider { - - @Override - protected IDocument createDocument(Object element) throws CoreException { - - IDocument document = super.createDocument(element); - //IDocumentPartitioner partitioner = createDocumentPartitioner(); - IDocumentPartitioner partitioner = new ImpexDocumentPartitioner(); - - if ((document instanceof IDocumentExtension3 extension3)) { - extension3.setDocumentPartitioner(Activator.IMPEX_PARTITIONING, partitioner); - } - else { - document.setDocumentPartitioner(partitioner); - } - - partitioner.connect(document); - return document; - } - - //private static IDocumentPartitioner createDocumentPartitioner() { - - //return new FastPartitioner(new ImpexPartitionScanner(), ImpexPartitionScanner.PARTITIONS); - //} -} diff --git a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/ImpexDocumentPartitioner.java b/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/ImpexDocumentPartitioner.java deleted file mode 100644 index c68899cd..00000000 --- a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/ImpexDocumentPartitioner.java +++ /dev/null @@ -1,186 +0,0 @@ -/******************************************************************************* - * Copyright 2020 SAP - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy - * of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - ******************************************************************************/ -package com.hybris.impexformatter; - -import java.util.ArrayList; -import java.util.List; - -import org.eclipse.core.runtime.Assert; -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.DocumentEvent; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IDocumentPartitioner; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.ITypedRegion; -import org.eclipse.jface.text.TypedRegion; - -public class ImpexDocumentPartitioner implements IDocumentPartitioner { - - public static final String IMPEX_DATA = "__y_impex_data"; - public static final String IMPEX_COMMENT = "__y_impex_comment"; - public static final String IMPEX_INSTRUCTION = "__y_impex_instruction"; - public static final String IMPEX_HEADER = "__y_impex_header"; - private IDocument fDocument; - - public ImpexDocumentPartitioner() { - // intended to be empty - } - - @Override - public void connect(IDocument document) { - Assert.isNotNull(document); - fDocument = document; - } - - @Override - public String getContentType(int offset) { - - try { - IRegion lineInfo = fDocument.getLineInformationOfOffset(offset); - String line = fDocument.get(lineInfo.getOffset(), lineInfo.getLength()); - - if (line.startsWith("INSERT ") || line.startsWith("INSERT_UPDATE ") || line.startsWith("UPDATE ") || line.startsWith("REMOVE ")) { - return ImpexDocumentPartitioner.IMPEX_HEADER; - } - if (line.startsWith("\"#%") || line.startsWith("#%")) { - return ImpexDocumentPartitioner.IMPEX_INSTRUCTION; - } - if (line.startsWith("#")) { - return ImpexDocumentPartitioner.IMPEX_COMMENT; - } - if (line.startsWith(";")) { - return ImpexDocumentPartitioner.IMPEX_DATA; - } - if (line.startsWith("$")) { - // need to handle macros, user rights $START_USERRIGHTS - return null; - } - } - catch (BadLocationException e) { - Activator.logError("BadLocationException", e); - } - - return IDocument.DEFAULT_CONTENT_TYPE; - } - - private int getLineEndOffset(int line, IDocument document) throws BadLocationException { - - int length = document.getLineLength(line); - int start = document.getLineOffset(line); - return start + length - 1; - } - - @Override - public ITypedRegion getPartition(int arg0) { - /* - * Never gets called because this class implements IDocumentPartitioner - * rather than IDocumentPartitionerExtension2 which is required for - * IDocumentExtension3 - * Confused ?? Me too... - */ - return new TypedRegion(0, fDocument.getLength(), IMPEX_HEADER); - } - - @Override - public ITypedRegion[] computePartitioning(int offset, int length) { - /* - * Never gets called because this class implements IDocumentPartitioner - * rather than IDocumentPartitionerExtension2 which is required for - * IDocumentExtension3 - * Confused ?? Me too... - */ - List list = new ArrayList(); - try { - int start; - int nextOffset; - boolean isHeader = true; - int docLength = fDocument.getLength(); - - if (offset == 0) { - nextOffset = getLineEndOffset(1, fDocument); - list.add(new TypedRegion(0, nextOffset + 1, IMPEX_HEADER)); - - int i = 1; - while (nextOffset + 1 < docLength) { - start = nextOffset+ 1; - if (Character.isDigit(fDocument.getChar(start))) { - isHeader = true; - } - else { - isHeader = false; - } - - nextOffset = getLineEndOffset(i + 1, fDocument); - if (isHeader) { - list.add(new TypedRegion(start, nextOffset - start + 1, IMPEX_INSTRUCTION)); - } - else { - list.add(new TypedRegion(start, nextOffset - start + 1, IMPEX_DATA)); - } - i = i + 1; - } - } - else { - if (Character.isDigit(fDocument.getChar(offset))) { - isHeader = true; - } - else { - isHeader = false; - } - - if (isHeader) { - list.add(new TypedRegion(offset, length, IMPEX_HEADER)); - } - else { - list.add(new TypedRegion(offset, length, IMPEX_DATA)); - } - } - - } - catch (BadLocationException ble) { - Activator.logError("BadLocationException", ble); - } - - if (list.isEmpty()) { - list.add(new TypedRegion(offset, length, null)); - } - - TypedRegion[] result = new TypedRegion[list.size()]; - list.toArray(result); - return result; - } - - @Override - public void disconnect() { - // Intentionally left blank - } - - @Override - public void documentAboutToBeChanged(DocumentEvent arg0) { - // Intentionally left blank - } - - @Override - public boolean documentChanged(DocumentEvent arg0) { - return false; - } - - @Override - public String[] getLegalContentTypes() { - return new String[] {}; - } - -} diff --git a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/actions/CommentAction.java b/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/actions/CommentAction.java deleted file mode 100755 index cee20c58..00000000 --- a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/actions/CommentAction.java +++ /dev/null @@ -1,36 +0,0 @@ -/******************************************************************************* - * Copyright 2020 SAP - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy - * of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - ******************************************************************************/ -package com.hybris.impexformatter.actions; - -import org.eclipse.jface.action.IAction; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.ui.IActionDelegate; - -public class CommentAction implements IActionDelegate { - - @Override - public void run(IAction arg0) { - // TODO Auto-generated method stub - - } - - @Override - public void selectionChanged(IAction arg0, ISelection arg1) { - // TODO Auto-generated method stub - - } - -} diff --git a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/actions/Formatter.java b/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/actions/Formatter.java deleted file mode 100755 index 841bb789..00000000 --- a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/actions/Formatter.java +++ /dev/null @@ -1,221 +0,0 @@ -/******************************************************************************* - * Copyright 2020 SAP - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy - * of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - ******************************************************************************/ -package com.hybris.impexformatter.actions; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.StringWriter; -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; - -import com.google.common.collect.Lists; -import com.hybris.impexformatter.Activator; - -public class Formatter { - - public final static String HEADER_MODE = "(UPDATE|INSERT_UPDATE|INSERT|REMOVE|$START_USERRIGHTS).*"; - public final static List HEADER_MODE_PROPOSALS = Lists.newArrayList("INSERT_UPDATE","UPDATE", "INSERT", "REMOVE"); - - public final static List INSTRUCTION_CLASS_PROPOSALS = Lists.newArrayList("impex.", "if:", "endif:", "afterEach:", "afterEach:end", "beforeEach:", "beforeEach:end"); - public final static List INSTRUCTION_CLASS_PROPOSALS_SPACE = Lists.newArrayList("if:", "afterEach:", "beforeEach:"); - - public final static List IMPEX_KEYWORDS_ATTRIBUTES = Lists.newArrayList("batchmode", "cacheUnique", "processor", "parallel", - "translator", "default", "lang", "unique", "allowNull", "ignoreNull", "dateformat", "numberformat", - "collection-delimiter", "path-delimiter", "key2value-delimiter", "map-delimiter", "mode", "cellDecorator", "virtual", "ignoreKeyCase", "alias", "pos", "forceWrite"); - public final static List IMPEX_KEYWORDS_ATTRIBUTES_BOOLEAN = Lists.newArrayList("allowNull", "batchmode", "cacheUnique", "forceWrite", "ignoreKeyCase", "ignoreNull", - "unique", "virtual"); - - public final static List KEYWORDS_VALUES = Lists.newArrayList("true", "false", "append", "remove"); - - public final static String LINE_SEPARATOR = "line.separator"; - private final static String DOUBLE_QUOTATION_MARK = "\"\""; - - private final static String SEMICOLON_MARK = ";"; - private final static String PERCENT_MARK = "%"; - private final static String FIRST_LFT_FORMATTER = "%-"; - private final static String LFT_FORMATTER = " %-"; - private final static String COL_STR_FORMATTER = "s;"; - private final static String STR_FORMATTER = "s"; - private final static String NEW_LINE_MARK = "\n"; - - public static String formatData(BufferedReader reader, StringWriter writer, String line) throws IOException { - ArrayList columnMaxWidth = new ArrayList<>(); - List dataBlock = new ArrayList<>(); - try { - LineData header = new LineData(line); - dataBlock.add(header); - // assign for each column max width - at the begging it's width of header column - for (int col = 0; col < header.numberOfCol; col++) { - columnMaxWidth.add(col, header.colData.get(col).length()); - } - // if column value is written in more than row remembered is index of column where value is - // helpful when value ends in later rows and after it are more data, so these data should be formatted in - // rights columns - int lastColIndex = 0; - while ((line = reader.readLine()) != null) { - // check if line contains column data - if (line.startsWith(SEMICOLON_MARK) || line.trim().startsWith(SEMICOLON_MARK)) { - LineData dataRow = new LineData(line); - dataBlock.add(dataRow); - // iterate through all columns in new row and check if width is higher than max width - for (int columnIndex = 0; columnIndex < dataRow.numberOfCol; columnIndex++) { - // check if data is a string - starts with " and not ends in the same line - if (dataRow.colData.get(columnIndex).startsWith(LineData.QUOTATION_MARK) - && !((dataRow.colData.get(columnIndex).endsWith(LineData.QUOTATION_MARK) && !(dataRow.colData - .get(columnIndex).endsWith(DOUBLE_QUOTATION_MARK))) || (dataRow.colData - .get(columnIndex).endsWith( - LineData.QUOTATION_MARK + SEMICOLON_MARK) && !(dataRow.colData - .get(columnIndex).endsWith(DOUBLE_QUOTATION_MARK - + SEMICOLON_MARK))))) { - // assign index of last column in the row which can be not last for particular value line - lastColIndex = columnIndex; - } - // check if column index is lower than size of array - // if not number of columns in new row is higher than size of this array - if (columnIndex <= columnMaxWidth.size() - 1) { - // check if current column is longer than column assigned to max width array - if (columnMaxWidth.get(columnIndex) < (dataRow.colData.get(columnIndex).length())) { - columnMaxWidth.set(columnIndex, (dataRow.colData.get(columnIndex).length())); - } - } else { - // if there are more columns add new max width - columnMaxWidth.add(columnIndex, (dataRow.colData.get(columnIndex).length())); - } - } - } else if ("".equals(line)) { - // add line if empty - dataBlock.add(null); - } else if (line.startsWith(LineData.HASH_MARK)) { - // add line if comment - dataBlock.add(new LineData(line)); - } else if (line.startsWith(LineData.QUOTATION_HASH_PERCENT_MARK)) { // check if this is block of code - // check if quotation mark not at last place in the line - dataBlock.add(new LineData(line)); - if (line.lastIndexOf(LineData.QUOTATION_MARK) <= 0) { - boolean ifContinue = true; - // while line value is in next row - do { - line = reader.readLine(); - if (line != null) { - LineData lineData = new LineData(line); - dataBlock.add(lineData); - if (lineData.singleQuotationIndex > -1) { - ifContinue = false; - } - } - else { - ifContinue = false; - } - } while (ifContinue); - } - } else if (line.length() > 0) { - LineData lineData = new LineData(line); - if (line.toUpperCase(Locale.ENGLISH).matches(HEADER_MODE)) { - break; - } - // if line is continue of line value added somewhere before - if (lastColIndex > 0) { - // if there is single quotation in line check if there are more data - semicolon after quotation - // mark - if (lineData.singleQuotationIndex > -1) { - if (line.indexOf(SEMICOLON_MARK, lineData.singleQuotationIndex) > 0) { - // assign index of column where long data is assigned - lineData.longValueColIndex = lastColIndex; - } - } - } - dataBlock.add(lineData); - } else { - break; - } - } - - } - catch (IOException e) { - Activator.logError("IOException", e); - } - formatLines(columnMaxWidth, writer, dataBlock); - return line; - } - - public static void formatLines(ArrayList columnMaxWidth, StringWriter writer, List dataBlock) - throws IOException { - int firstItemLength = dataBlock.getFirst().colData.getFirst().length(); - for (LineData row : dataBlock) { - if (row != null) { - String format = FIRST_LFT_FORMATTER + firstItemLength + STR_FORMATTER; - // if row starts with ; - if (row.colData.getFirst().toString().startsWith(SEMICOLON_MARK)) { - // remove semicolon from first value - row.colData.set(0, row.colData.getFirst().substring(0, row.colData.getFirst().length() - 1)); - format = PERCENT_MARK + firstItemLength + COL_STR_FORMATTER; - } else if (row.numberOfCol > 1) { // if row at the beginning has end of long value - if (row.colData.getFirst().toString().endsWith(SEMICOLON_MARK)) { - row.colData.set(0, row.colData.getFirst().substring(0, row.colData.getFirst().length() - 1)); - } - if (row.longValueColIndex <= 0) { - format = FIRST_LFT_FORMATTER + firstItemLength + COL_STR_FORMATTER; - } - } - if (row.longValueColIndex > 0) { - // size of first item plus number of columns (spaces) - int widthToNextCol = firstItemLength + row.longValueColIndex; - // widthToNextCol + max width of next columns - for (int i = 1; i <= row.longValueColIndex; i++) { - int colSize = columnMaxWidth.get(i) + 1; - widthToNextCol += colSize; - } - format = FIRST_LFT_FORMATTER + widthToNextCol + COL_STR_FORMATTER; - } - - for (int singleData = 1; singleData < row.numberOfCol; singleData++) { - int formatWidth; - if (columnMaxWidth.size() >= singleData) { - formatWidth = columnMaxWidth.get(singleData); - } else { - formatWidth = row.colData.get(singleData).length(); - columnMaxWidth.add(singleData, formatWidth); - } - - if (row.longValueColIndex > 0) { - int colRealIndex = row.longValueColIndex + singleData; - // if column index is higher than max width array size at it to this array - if (columnMaxWidth.size() <= colRealIndex) { - columnMaxWidth.add(colRealIndex, (row.colData.get(singleData).length())); - } - formatWidth = columnMaxWidth.get(colRealIndex); - } - if (formatWidth == 0) { - formatWidth = 1; - } - String colValue = row.colData.get(singleData); - if (colValue.endsWith(SEMICOLON_MARK)) { - row.colData.set(singleData, colValue.substring(0, colValue.length() - 1)); - format += LFT_FORMATTER + formatWidth + COL_STR_FORMATTER; - } else { - format += LFT_FORMATTER + formatWidth + STR_FORMATTER; - } - } - format += NEW_LINE_MARK; - writer.append(String.format(format, row.colData.toArray())); - } else { - writer.write(System.getProperty(LINE_SEPARATOR)); - } - } - } - -} diff --git a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/actions/LineData.java b/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/actions/LineData.java deleted file mode 100755 index 676b2a29..00000000 --- a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/actions/LineData.java +++ /dev/null @@ -1,99 +0,0 @@ -/******************************************************************************* - * Copyright 2020 SAP - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy - * of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - ******************************************************************************/ -package com.hybris.impexformatter.actions; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -/** - * LineData DTO - item used for line details - * - */ -public class LineData { - - public static final String QUOTATION_MARK = "\""; - public static final char HASH_CHAR = '#'; - public static final char QUOTATION_CHAR = '\"'; - public static final String HASH_MARK = "#"; - private final String SPLIT_VAL = "(?<=;)"; - public static final String QUOTATION_HASH_PERCENT_MARK = "\"#%"; - private final static String SEMICOLON_MARK = ";"; - - String line; - List colData = new ArrayList<>(); - int singleQuotationIndex; - int numberOfCol; - int longValueColIndex = -1; - - public LineData(String line) { - this.line = line; - if (line.startsWith(HASH_MARK) || line.startsWith(QUOTATION_HASH_PERCENT_MARK)) { - this.colData = Arrays.asList(line); - } - else { - List datas = Arrays.asList(line.split(SPLIT_VAL, -1)); - if (datas.size() > 1) { - for (int i = 0; i < datas.size(); i++) { - boolean ifends = false; - if (datas.get(i).endsWith(SEMICOLON_MARK)) { - datas.set(i, datas.get(i).substring(0, datas.get(i).length() - 1)); - ifends = true; - } - String dat = datas.get(i).trim(); - if (ifends) { - dat = dat + SEMICOLON_MARK; - } - this.colData.add(dat); - } - } - else { - this.colData = datas; - } - } - this.singleQuotationIndex = getSingleQuotationIndex(line); - this.numberOfCol = this.colData.size(); - - } - - /** - * returns index of single quotation in line Function is checking if there is quotation in line, If yes than it - * checks if next char isn't quotation or hash - * - */ - private int getSingleQuotationIndex(String line) { - int singleQuotationIndex = -1; - int quotationIndex = line.indexOf(QUOTATION_MARK); - // check if there is quotation in line - while (quotationIndex >= 0) { - int nextIndex = quotationIndex + 1; - if (line.length() > nextIndex) { - char afterQuotationChar = line.charAt(nextIndex); - // if it's "" or "# than is not single quotation - if ((afterQuotationChar != QUOTATION_CHAR) && (afterQuotationChar != HASH_CHAR)) { - singleQuotationIndex = quotationIndex; - } - } - else { - singleQuotationIndex = quotationIndex; - } - // check if there is quotation more than 2 places after last quotation - quotationIndex = line.indexOf(QUOTATION_MARK, nextIndex + 1); - } - return singleQuotationIndex; - } - -} diff --git a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/assistprocessors/ImpexCommandContentAssistProcessor.java b/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/assistprocessors/ImpexCommandContentAssistProcessor.java deleted file mode 100755 index e42ec7a7..00000000 --- a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/assistprocessors/ImpexCommandContentAssistProcessor.java +++ /dev/null @@ -1,237 +0,0 @@ -/******************************************************************************* - * Copyright 2020 SAP - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy - * of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - ******************************************************************************/ -package com.hybris.impexformatter.assistprocessors; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Optional; - -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.ITextViewer; -import org.eclipse.jface.text.contentassist.CompletionProposal; -import org.eclipse.jface.text.contentassist.ContextInformationValidator; -import org.eclipse.jface.text.contentassist.ICompletionProposal; -import org.eclipse.jface.text.contentassist.IContentAssistProcessor; -import org.eclipse.jface.text.contentassist.IContextInformation; -import org.eclipse.jface.text.contentassist.IContextInformationValidator; - -import com.google.common.base.Function; -import com.google.common.base.Predicates; -import com.google.common.collect.Collections2; -import com.google.common.collect.Lists; -import com.hybris.impexformatter.Activator; -import com.hybris.impexformatter.actions.Formatter; -import com.hybris.impexformatter.utils.StringHelper; - -public class ImpexCommandContentAssistProcessor implements IContentAssistProcessor { - - private String exMsg = null; - private IContextInformationValidator iciv; - - public ImpexCommandContentAssistProcessor() { - super(); - iciv = new ContextInformationValidator(this); - } - - @Override - public ICompletionProposal[] computeCompletionProposals(ITextViewer itv, int cursorPosition) { - - IDocument iDoc = itv.getDocument(); - IRegion lineInfo; - try { - lineInfo = iDoc.getLineInformationOfOffset(cursorPosition); - String line = iDoc.get(lineInfo.getOffset(), lineInfo.getLength()); - List keywords = Formatter.HEADER_MODE_PROPOSALS; - List autoCompProposals = new ArrayList<>(); - //If the line is empty, propose Headers and remove leading whitespace... - if (line.trim().length() == 0) { - - for (String keyword : keywords) { - autoCompProposals.add(new CompletionProposal(keyword + " ", cursorPosition - line.length(), line.length(), keyword.length() + 1)); - } - if (!autoCompProposals.isEmpty()) { - return (ICompletionProposal[]) autoCompProposals.toArray(new ICompletionProposal[autoCompProposals.size()]); - } - } - - //Line isn't empty... - for (String keyword : keywords) { - if (StringHelper.findMatches(keyword, line)) { - return standardMethod(itv, cursorPosition, keywords, autoCompProposals); - } - } - } - catch (BadLocationException ble) { - Activator.getDefault().log("could not compute proposals", ble); - } - return null; - } - - private ICompletionProposal[] standardMethod(ITextViewer viewer, int offset, List keywords, List autoCompProposals) { - - int index = offset - 1; - StringBuffer prefix = new StringBuffer(); - IDocument document = viewer.getDocument(); - - while (index > 0) { - try { - char prev = document.getChar(index); - if (Character.isWhitespace(prev)) { - break; - } - prefix.insert(0, prev); - index--; - } - catch (BadLocationException ble) { - Activator.getDefault().log("could not get char", ble); - } - } - - if (prefix.length() > 0) { - String word = prefix.toString(); - // limit to attributes - if (containsOpenBracket(word)) { - autoCompProposals.addAll(addHeaderAttributes(word, offset)); - } - for (String keyword : keywords) { - if (StringHelper.findMatches(keyword, word)) { - autoCompProposals.add(new CompletionProposal(keyword + " ", index + 1, offset - (index + 1), keyword.length() + 1)); - } - } - } - else { - // propose header keywords - proposeHeaderOperands(offset, document, autoCompProposals); - } - - if (!autoCompProposals.isEmpty()) { - return (ICompletionProposal[]) autoCompProposals.toArray(new ICompletionProposal[autoCompProposals.size()]); - } - return null; - - } - - private Collection addHeaderAttributes(String oldWord, int offset) { - - List keywords = Formatter.IMPEX_KEYWORDS_ATTRIBUTES; - Collection result = Lists.newArrayList(); - int bracketPos = Optional.ofNullable(oldWord).orElse("").lastIndexOf("["); - int wordLength = oldWord.length(); - int replacementPos = wordLength - bracketPos; - if (bracketPos > -1) { - String word = oldWord.substring(bracketPos); - for (String keyword : keywords) { - if (StringHelper.findMatches(keyword, word)) { - result.add(new CompletionProposal(keyword + "=", (offset - replacementPos) + 1, word.length(), keyword.length() + 1)); - } - } - } - - return result; - - } - - /** - * Null-safe open-bracket character finder - * @param word - main string which is used for search - * @return return {@code true} when contains open bracket in text. - */ - private boolean containsOpenBracket(String word) { - return Optional.ofNullable(word).orElse("").contains("["); - } - - private void proposeHeaderOperands(int offset, IDocument document, List proposals) { - - String line = getCurrentLine(document, offset); - if (!containsHeader(line)) { - - for (String keyword : Formatter.HEADER_MODE_PROPOSALS) { - proposals.add(new CompletionProposal(keyword + " ", offset, 0, keyword.length() + 1)); - } - } - } - - @Override - public IContextInformation[] computeContextInformation(ITextViewer viewer, int cursorPosition) { - - exMsg = "No Context Information available"; - return null; - } - - @Override - public char[] getCompletionProposalAutoActivationCharacters() { - - return null; - } - - @Override - public char[] getContextInformationAutoActivationCharacters() { - - return null; - } - - @Override - public String getErrorMessage() { - return exMsg; - } - - @Override - public IContextInformationValidator getContextInformationValidator() { - - return iciv; - } - - public String getCurrentLine(IDocument document, int offset) { - - final String docContent = document.get(); - String line = ""; - IRegion currentRegion = null; - int posOffset = offset; - try { - currentRegion = document.getLineInformationOfOffset(offset); - - posOffset = currentRegion.getOffset() + currentRegion.getLength(); - - line = docContent.substring(currentRegion.getOffset(), posOffset); - } - catch (BadLocationException ble) { - Activator.getDefault().log("could not get current line", ble); - } - - return line; - } - - public boolean containsHeader(String line) { - String[] tokens = line.split(" "); - ArrayList tokenList = Lists.newArrayList(tokens); - - // uppercase tokens - Collections2.transform(tokenList, new Function() { - - @Override - public String apply(String arg) { - return arg.toUpperCase(); - } - }); - - Collection result = Collections2.filter(tokenList, Predicates.in(Formatter.HEADER_MODE_PROPOSALS)); - return !result.isEmpty(); - } - -} diff --git a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/assistprocessors/ImpexCommentContentAssistProcessor.java b/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/assistprocessors/ImpexCommentContentAssistProcessor.java deleted file mode 100644 index 5b623cf1..00000000 --- a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/assistprocessors/ImpexCommentContentAssistProcessor.java +++ /dev/null @@ -1,71 +0,0 @@ -/******************************************************************************* - * Copyright 2020 SAP - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy - * of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - ******************************************************************************/ -package com.hybris.impexformatter.assistprocessors; - -import org.eclipse.jface.text.ITextViewer; -import org.eclipse.jface.text.contentassist.ContextInformationValidator; -import org.eclipse.jface.text.contentassist.ICompletionProposal; -import org.eclipse.jface.text.contentassist.IContentAssistProcessor; -import org.eclipse.jface.text.contentassist.IContextInformation; -import org.eclipse.jface.text.contentassist.IContextInformationValidator; - -public class ImpexCommentContentAssistProcessor implements IContentAssistProcessor { - - private IContextInformationValidator iciv; - private String exMsg = null; - - public ImpexCommentContentAssistProcessor() { - super(); - iciv = new ContextInformationValidator(this); - } - - @Override - public ICompletionProposal[] computeCompletionProposals(ITextViewer textViewer, int documentOffset) { - - return null; - } - - @Override - public IContextInformation[] computeContextInformation(ITextViewer textViewer, int documentOffset) { - exMsg = "No Context Information available"; - return null; - } - - @Override - public char[] getCompletionProposalAutoActivationCharacters() { - - return null; - } - - @Override - public char[] getContextInformationAutoActivationCharacters() { - - return null; - } - - @Override - public IContextInformationValidator getContextInformationValidator() { - - return iciv; - } - - @Override - public String getErrorMessage() { - - return exMsg; - } - -} diff --git a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/assistprocessors/ImpexDataContentAssistProcessor.java b/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/assistprocessors/ImpexDataContentAssistProcessor.java deleted file mode 100644 index 66727d5e..00000000 --- a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/assistprocessors/ImpexDataContentAssistProcessor.java +++ /dev/null @@ -1,72 +0,0 @@ -/******************************************************************************* - * Copyright 2020 SAP - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy - * of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - ******************************************************************************/ -package com.hybris.impexformatter.assistprocessors; - -import org.eclipse.jface.text.ITextViewer; -import org.eclipse.jface.text.contentassist.ContextInformationValidator; -import org.eclipse.jface.text.contentassist.ICompletionProposal; -import org.eclipse.jface.text.contentassist.IContentAssistProcessor; -import org.eclipse.jface.text.contentassist.IContextInformation; -import org.eclipse.jface.text.contentassist.IContextInformationValidator; - -public class ImpexDataContentAssistProcessor implements IContentAssistProcessor { - - private IContextInformationValidator iciv; - private String exMsg = null; - - public ImpexDataContentAssistProcessor() { - super(); - iciv = new ContextInformationValidator(this); - } - - @Override - public ICompletionProposal[] computeCompletionProposals(ITextViewer textViewer, int documentOffset) { - - //TODO - could include $variables - return null; - } - - @Override - public IContextInformation[] computeContextInformation(ITextViewer textViewer, int documentOffset) { - exMsg = "No Context Information available"; - return null; - } - - @Override - public char[] getCompletionProposalAutoActivationCharacters() { - - return null; - } - - @Override - public char[] getContextInformationAutoActivationCharacters() { - - return null; - } - - @Override - public IContextInformationValidator getContextInformationValidator() { - - return iciv; - } - - @Override - public String getErrorMessage() { - - return exMsg; - } - -} diff --git a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/assistprocessors/ImpexInstructionContentAssistProcessor.java b/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/assistprocessors/ImpexInstructionContentAssistProcessor.java deleted file mode 100755 index f66ca7ac..00000000 --- a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/assistprocessors/ImpexInstructionContentAssistProcessor.java +++ /dev/null @@ -1,142 +0,0 @@ -/******************************************************************************* - * Copyright 2020 SAP - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy - * of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - ******************************************************************************/ -package com.hybris.impexformatter.assistprocessors; - -import java.lang.invoke.MethodHandles; -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; -import java.util.logging.Level; -import java.util.logging.Logger; - -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.ITextViewer; -import org.eclipse.jface.text.contentassist.CompletionProposal; -import org.eclipse.jface.text.contentassist.ContextInformationValidator; -import org.eclipse.jface.text.contentassist.ICompletionProposal; -import org.eclipse.jface.text.contentassist.IContentAssistProcessor; -import org.eclipse.jface.text.contentassist.IContextInformation; -import org.eclipse.jface.text.contentassist.IContextInformationValidator; - -import com.google.common.collect.Lists; -import com.hybris.impexformatter.actions.Formatter; - -public class ImpexInstructionContentAssistProcessor implements IContentAssistProcessor { - - private final static Logger LOG = Logger.getLogger(MethodHandles.lookup().lookupClass().toString()); - private IContextInformationValidator iciv; - private String exMsg = null; - - public ImpexInstructionContentAssistProcessor() { - super(); - iciv = new ContextInformationValidator(this); - } - - @Override - public ICompletionProposal[] computeCompletionProposals(ITextViewer itv, int cursorPosition) { - - int counter = cursorPosition - 1; - StringBuffer prefix = new StringBuffer(); - IDocument iDoc = itv.getDocument(); - - while (counter > 0) { - try { - char prev = iDoc.getChar(counter); - if (Character.isWhitespace(prev)) { - break; - } - prefix.insert(0, prev); - counter--; - } - catch (BadLocationException ble) { - LOG.log(Level.WARNING, "could not get char", ble); - } - } - - List autoCompProposals = new ArrayList<>(); - List keywords = Lists.newArrayList(Formatter.INSTRUCTION_CLASS_PROPOSALS); - - if (prefix.length() > 0) { - String word = prefix.toString(); - // limit to attributes - for (String keyword : keywords) { - if (keyword.toUpperCase(Locale.ENGLISH).startsWith(word.toUpperCase(Locale.ENGLISH)) && word.length() < keyword.length()) { - autoCompProposals.add(new CompletionProposal(keyword + " ", counter + 1, cursorPosition - (counter + 1), keyword.length() + 1)); - } - } - } - else { - // Add all - for (String keyword : keywords) { - autoCompProposals.add(new CompletionProposal(keyword + " ", counter + 1, cursorPosition - (counter + 1), keyword.length() + 1)); - } - } - if (!autoCompProposals.isEmpty()) { - return (ICompletionProposal[]) autoCompProposals.toArray(new ICompletionProposal[autoCompProposals.size()]); - } - - return new ICompletionProposal[0] ; - } - - @Override - public IContextInformation[] computeContextInformation(ITextViewer itv, int cursorPosition) { - exMsg = "No Context Information available"; - return null; - } - - @Override - public char[] getCompletionProposalAutoActivationCharacters() { - - return null; - } - - @Override - public char[] getContextInformationAutoActivationCharacters() { - - return null; - } - - @Override - public String getErrorMessage() { - return exMsg; - } - - @Override - public IContextInformationValidator getContextInformationValidator() { - return iciv; - } - - public String getCurrentLine(IDocument document, int cursorPosition, boolean toCursor) { - final String docContent = document.get(); - String line = ""; - IRegion currentRegion = null; - int posOffset = cursorPosition; - try { - currentRegion = document.getLineInformationOfOffset(cursorPosition); - if (toCursor == false) { - posOffset = currentRegion.getOffset() + currentRegion.getLength(); - } - line = docContent.substring(currentRegion.getOffset(), posOffset); - } - catch (BadLocationException ble) { - LOG.log(Level.WARNING, "could not get current line", ble); - } - return line; - } - -} diff --git a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/assistprocessors/ImpexTypeAttributeContentAssistProcessor.java b/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/assistprocessors/ImpexTypeAttributeContentAssistProcessor.java deleted file mode 100644 index bc3ff346..00000000 --- a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/assistprocessors/ImpexTypeAttributeContentAssistProcessor.java +++ /dev/null @@ -1,377 +0,0 @@ -/******************************************************************************* - * Copyright 2020 SAP - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy - * of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - ******************************************************************************/ -package com.hybris.impexformatter.assistprocessors; - -import static com.hybris.impexformatter.utils.StringHelper.findMatches; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.Optional; - -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.ITextViewer; -import org.eclipse.jface.text.contentassist.CompletionProposal; -import org.eclipse.jface.text.contentassist.ContextInformationValidator; -import org.eclipse.jface.text.contentassist.ICompletionProposal; -import org.eclipse.jface.text.contentassist.IContentAssistProcessor; -import org.eclipse.jface.text.contentassist.IContextInformation; -import org.eclipse.jface.text.contentassist.IContextInformationValidator; - -import com.google.common.collect.Lists; -import com.hybris.impexformatter.Activator; -import com.hybris.impexformatter.actions.Formatter; - -public class ImpexTypeAttributeContentAssistProcessor implements IContentAssistProcessor { - - private Activator plugin; - private IContextInformationValidator iciv; - private String exMsg = null; - - public ImpexTypeAttributeContentAssistProcessor() { - super(); - iciv = new ContextInformationValidator(this); - } - - @Override - public ICompletionProposal[] computeCompletionProposals(ITextViewer itv, int cursorPosition) { - - //TODO - //Add variables defined at top of page to attribute list???? - - IDocument document = itv.getDocument(); - - try { - String thisAttrib = ""; - - IRegion lineInfo = document.getLineInformationOfOffset(cursorPosition); - String line = document.get(lineInfo.getOffset(), lineInfo.getLength()); - if (line.endsWith("]") || line.endsWith(")")) { - line = line.substring(0, line.length() -1); - } - - thisAttrib = line.substring(line.indexOf(" ") + 1, line.length()); - - String[] headerParts = Optional.ofNullable(thisAttrib).orElse("").split(";"); - - - - - boolean showTypes = false; - boolean showAttributes = false; - boolean showKeywords = false; - - int numberOfParts = headerParts.length; - String currentPart = ""; - - //Do the easy checks first... - if (thisAttrib.trim().isEmpty()) { - //If empty, show types - showTypes = true; - } - else { - currentPart = headerParts[numberOfParts -1]; - currentPart = currentPart.trim(); - - if (thisAttrib.endsWith(";") || thisAttrib.endsWith("(")) { - showAttributes = true; - } - else if (thisAttrib.endsWith("[")) { - showKeywords = true; - } - else if (thisAttrib.endsWith("=")) { - showKeywords = true; - } - else { - //Now the more complicated checks... - if (numberOfParts == 1) { - showTypes = true; - } - else { - //......... - if (currentPart.contains("[") && !currentPart.contains("]")) { - showKeywords = true; - currentPart = currentPart.substring(currentPart.lastIndexOf("[") + 1, currentPart.length()); - } - else { - showAttributes = true; - } - } - } - } - - if (showTypes || showAttributes) { - if (plugin == null) { - plugin = Activator.getDefault(); - } - } - - List autoSuggests = null; - - if (showTypes) { - List allTypeNames = plugin.getAllTypeNames(); - if (thisAttrib.trim().isEmpty()) { - //If currWord is empty, return all Types - autoSuggests = new ArrayList<>(allTypeNames.size()); - autoSuggests.addAll(allTypeNames); - } - else { - //If not empty, filter based on currWord - autoSuggests = new ArrayList<>(); - for (String typeCode : allTypeNames) { - if (findMatches(currentPart, typeCode)) { - autoSuggests.add(typeCode); - } - } - } - } - - boolean endingSemiColon = true; - if (showAttributes) { - String typeName = headerParts[0]; - - String lastAttribute = plugin.getAttributeName(typeName, currentPart); - if (lastAttribute != null) { - endingSemiColon = false; - } - - List attributeNames = plugin.getAllAttributeNames(typeName); - - if (currentPart.trim().isEmpty() || thisAttrib.endsWith(";") || thisAttrib.endsWith("(") || !endingSemiColon) { - //If currentPart is empty, return all Attributes not already used - autoSuggests = new ArrayList<>(attributeNames.size()); - for (String attributeQualifier : attributeNames) { - if (!thisAttrib.contains(attributeQualifier + ";") - && !thisAttrib.contains(attributeQualifier + "(") - && !thisAttrib.contains(attributeQualifier + "[") - || thisAttrib.endsWith("(")) { - autoSuggests.add(attributeQualifier); - } - } - } - else { - //If not empty, filter based on currentPart - autoSuggests = new ArrayList<>(); - for (String attributeQualifier : attributeNames) { - boolean insideBrackets = false; - if (currentPart.contains("(")) { - currentPart = currentPart.substring(currentPart.indexOf("(") + 1, currentPart.length()); - insideBrackets = true; - } - //If its inside brackets, include all attributes - //Otherwise, exclude those already used - - if (findMatches(attributeQualifier, currentPart)) { - if (insideBrackets) { - autoSuggests.add(attributeQualifier); - } - else { - //Dont add already used attribute - if (!thisAttrib.contains(attributeQualifier + ";") - && !thisAttrib.contains(attributeQualifier + "(") - && !thisAttrib.contains(attributeQualifier + "[") - || thisAttrib.endsWith("(")) { - autoSuggests.add(attributeQualifier); - } - } - } - } - } - } - - boolean includeEquals = true; - boolean includesComma = false; - - if (showKeywords) { - if (currentPart.trim().isEmpty() || thisAttrib.endsWith("[") || thisAttrib.endsWith(",")) { - if (thisAttrib.endsWith(",")) { - includesComma = true; - //already have 1, filter the list - autoSuggests = new ArrayList<>(); - String keywordName = thisAttrib.substring(thisAttrib.indexOf("[") + 1, thisAttrib.lastIndexOf("=")); - for (String keyword : Formatter.IMPEX_KEYWORDS_ATTRIBUTES) { - if (!keyword.equalsIgnoreCase(keywordName)) { - autoSuggests.add(keyword); - } - } - } - else { - autoSuggests = Formatter.IMPEX_KEYWORDS_ATTRIBUTES; - } - } - else if (currentPart.trim().endsWith("=")) { - if (currentPart.contains(",")) { - includesComma = true; - } - //code[unique= - String keywordName = ""; - if (includesComma) { - keywordName = currentPart.substring(currentPart.lastIndexOf(",") + 1, currentPart.lastIndexOf("=")); - } - else { - keywordName = currentPart.substring(currentPart.indexOf("[") + 1, currentPart.indexOf("=")); - } - if (keywordName.equalsIgnoreCase("mode")) { - autoSuggests = Lists.newArrayList("append", "remove"); - includeEquals = false; - } - else { - if (Formatter.IMPEX_KEYWORDS_ATTRIBUTES_BOOLEAN.contains(keywordName)) { - autoSuggests = Lists.newArrayList("true", "false"); - includeEquals = false; - } - } - } - else { - //If not empty, filter based on currentPart - autoSuggests = new ArrayList<>(); - for (String keyword : Formatter.IMPEX_KEYWORDS_ATTRIBUTES) { - if (findMatches(keyword, currentPart)) { - autoSuggests.add(keyword); - } - } - } - } - - ICompletionProposal[] autoCompProposals = null; - - if (autoSuggests != null && autoSuggests.size() > 0) { - Collections.sort(autoSuggests); - - if (showTypes) - autoCompProposals = typeProposals(cursorPosition, autoSuggests, thisAttrib, currentPart); - if (showAttributes) - autoCompProposals = attributeProposals(cursorPosition, autoSuggests, thisAttrib, currentPart, endingSemiColon); - if (showKeywords) - autoCompProposals = keywordProposals(cursorPosition, autoSuggests, thisAttrib, currentPart, includeEquals, includesComma); - exMsg = null; - } - - return autoCompProposals; - } - catch (BadLocationException ble) { - Activator.logError("BadLocationException", ble); - exMsg = ble.getMessage(); - return null; - } - - } - - private ICompletionProposal[] typeProposals(int cursorPosition, List autoSuggests, String thisAttrib, String currentPart) { - - int counter = 0; - ICompletionProposal[] suggestions = new ICompletionProposal[autoSuggests.size()]; - for (Iterator iter = autoSuggests.iterator(); iter.hasNext();) { - String autoSuggest = (String)iter.next(); - - //Each proposal contains the text to propose, as well as information about where to insert the text into the document. - suggestions[counter] = new CompletionProposal(autoSuggest + ";", cursorPosition - thisAttrib.length(), thisAttrib.length(), autoSuggest.length() + 1); - counter++; - } - return suggestions; - } - - private ICompletionProposal[] attributeProposals(int cursorPosition, List autoSuggests, String thisAttrib, String currentPart, boolean endingSemiColon) { - - int counter = 0; - ICompletionProposal[] suggestions = new ICompletionProposal[autoSuggests.size()]; - for (Iterator iter = autoSuggests.iterator(); iter.hasNext();) { - String autoSuggest = (String)iter.next(); - - //Each proposal contains the text to propose, as well as information about where to insert the text into the document. - if (thisAttrib.endsWith(";") || thisAttrib.endsWith("(") || !endingSemiColon) { - suggestions[counter] = new CompletionProposal(autoSuggest, cursorPosition, 0, autoSuggest.length()); - } - else { - suggestions[counter] = new CompletionProposal(autoSuggest, cursorPosition - currentPart.length(), currentPart.length(), autoSuggest.length()); - } - counter++; - } - return suggestions; - } - - private ICompletionProposal[] keywordProposals(int cursorPosition, List autoSuggests, String thisAttrib, String currentPart, boolean includeEquals, boolean includesComma) { - - int counter = 0; - ICompletionProposal[] suggestions = new ICompletionProposal[autoSuggests.size()]; - for (Iterator iter = autoSuggests.iterator(); iter.hasNext();) { - String autoSuggest = (String)iter.next(); - - //Each proposal contains the text to propose, as well as information about where to insert the text into the document. - if (thisAttrib.endsWith("[")) { - suggestions[counter] = new CompletionProposal(autoSuggest + "=", cursorPosition, 0, autoSuggest.length() + 1); - } - else { - if (includeEquals) { - if (includesComma) { - suggestions[counter] = new CompletionProposal(autoSuggest + "=", cursorPosition, 0, autoSuggest.length() + 1); - } - else { - suggestions[counter] = new CompletionProposal(autoSuggest + "=", cursorPosition - currentPart.length(), currentPart.length(), autoSuggest.length() + 1); - } - } - else if (includesComma) { - if (thisAttrib.endsWith("=")) { - suggestions[counter] = new CompletionProposal(autoSuggest, cursorPosition, 0, autoSuggest.length()); - } - else { - suggestions[counter] = new CompletionProposal(autoSuggest, cursorPosition - currentPart.length(), currentPart.length(), autoSuggest.length() + 1); - } - } - else { - suggestions[counter] = new CompletionProposal(autoSuggest, cursorPosition, 0, autoSuggest.length()); - } - } - counter++; - } - return suggestions; - } - - @Override - public IContextInformation[] computeContextInformation(ITextViewer itv, int cursorPosition) { - - exMsg = "No Context Information available"; - return null; - } - - @Override - public char[] getCompletionProposalAutoActivationCharacters() { - - return null; - } - - @Override - public char[] getContextInformationAutoActivationCharacters() { - - return null; - } - - @Override - public IContextInformationValidator getContextInformationValidator() { - - return iciv; - } - - @Override - public String getErrorMessage() { - - return exMsg; - } - -} diff --git a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/assistprocessors/ImpexTypeSystemContentAssistProcessor.java b/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/assistprocessors/ImpexTypeSystemContentAssistProcessor.java deleted file mode 100644 index 5ad42430..00000000 --- a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/assistprocessors/ImpexTypeSystemContentAssistProcessor.java +++ /dev/null @@ -1,367 +0,0 @@ -/******************************************************************************* - * Copyright 2020 SAP - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy - * of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - ******************************************************************************/ -package com.hybris.impexformatter.assistprocessors; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; - -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.ITextViewer; -import org.eclipse.jface.text.contentassist.CompletionProposal; -import org.eclipse.jface.text.contentassist.ContextInformationValidator; -import org.eclipse.jface.text.contentassist.ICompletionProposal; -import org.eclipse.jface.text.contentassist.IContentAssistProcessor; -import org.eclipse.jface.text.contentassist.IContextInformation; -import org.eclipse.jface.text.contentassist.IContextInformationValidator; - -import com.google.common.collect.Lists; -import com.hybris.impexformatter.Activator; -import com.hybris.impexformatter.actions.Formatter; -import com.hybris.impexformatter.utils.StringHelper; - -public class ImpexTypeSystemContentAssistProcessor implements IContentAssistProcessor { - - private Activator plugin; - private IContextInformationValidator iciv; - private String exMsg = null; - - public ImpexTypeSystemContentAssistProcessor() { - super(); - iciv = new ContextInformationValidator(this); - } - - @Override - public ICompletionProposal[] computeCompletionProposals(ITextViewer itv, int cursorPosition) { - - IDocument iDoc = itv.getDocument(); - - try { - IRegion lineInfo = iDoc.getLineInformationOfOffset(cursorPosition); - - int startOfLine = lineInfo.getOffset(); - int lineLength = lineInfo.getLength(); - int cursorPositionInLine = cursorPosition - startOfLine; - - String wholeLine = iDoc.get(startOfLine, lineLength); - String lineAfterCursor = iDoc.get(startOfLine + cursorPositionInLine, lineLength - cursorPositionInLine); - - String lineWithoutCommand = ""; - lineWithoutCommand = wholeLine.substring(wholeLine.indexOf(" ") + 1, wholeLine.length()); - - String lineWithoutCommandUpToCursor = lineWithoutCommand.substring(0, cursorPositionInLine - (wholeLine.indexOf(" ") + 1)); - - //before cursor: lineWithoutCommandUpToCursor - //after cursor: lineAfterCursor - String tempString = new StringBuilder(lineWithoutCommandUpToCursor).append(";").append(lineAfterCursor).toString(); - String[] headerParts = tempString.split(";"); - - boolean showTypes = false; - boolean showAttributes = false; - boolean showKeywords = false; - - int numberOfParts = headerParts.length; - String currentPart = ""; - int lastSemicolon = lineWithoutCommandUpToCursor.lastIndexOf(";"); - currentPart = lineWithoutCommandUpToCursor.substring(lastSemicolon + 1, lineWithoutCommandUpToCursor.length()); - currentPart = currentPart.trim(); - - //Do the easy checks first... - if (lineWithoutCommand.trim().isEmpty()) { - //If empty, show types - showTypes = true; - } - else { - if (currentPart.endsWith(";") || currentPart.endsWith("(")) { - showAttributes = true; - } - else if (currentPart.endsWith("[")) { - showKeywords = true; - } - else if (currentPart.endsWith("=")) { - showKeywords = true; - } - else { - //Now the more complicated checks... - if (numberOfParts == 1 && !currentPart.isEmpty()) { - showTypes = true; - } - else { - if (currentPart.contains("[") && !currentPart.contains("]")) { - showKeywords = true; - currentPart = currentPart.substring(currentPart.lastIndexOf("[") + 1, currentPart.length()); - } - else { - showAttributes = true; - } - } - } - } - - if (showTypes || showAttributes) { - if (plugin == null) { - plugin = Activator.getDefault(); - } - } - - List autoSuggests = null; - - if (showTypes) { - List allTypeNames = plugin.getAllTypeNames(); - if (currentPart.isEmpty()) { - //return all Types - autoSuggests = new ArrayList<>(allTypeNames.size()); - autoSuggests.addAll(allTypeNames); - } - else { - //If not empty, filter based on currentPart - autoSuggests = new ArrayList<>(); - for (String typeCode : allTypeNames) { - if (StringHelper.findMatches(typeCode, currentPart)) { - autoSuggests.add(typeCode); - } - } - } - } - - if (showAttributes) { - String typeName = headerParts[0]; - List attributeNames = plugin.getAllAttributeNames(typeName); - if (currentPart.isEmpty() || currentPart.endsWith(";") || currentPart.endsWith("(")) { - //return all Attributes not already used - autoSuggests = new ArrayList<>(attributeNames.size()); - for (String attributeQualifier : attributeNames) { - if (!lineWithoutCommand.contains(attributeQualifier + ";") - && !lineWithoutCommand.contains(";" + attributeQualifier) - || currentPart.endsWith("(")) { - autoSuggests.add(attributeQualifier); - } - } - } - else { - //If not empty, filter based on currentPart - autoSuggests = new ArrayList<>(); - for (String attributeQualifier : attributeNames) { - String tempCurrentPart = currentPart; - boolean insideBrackets = false; - if (currentPart.contains("(")) { - tempCurrentPart = currentPart.substring(currentPart.indexOf("(") + 1, currentPart.length()); - insideBrackets = true; - } - //If its inside brackets, include all attributes - //Otherwise, exclude those already used - - if (StringHelper.findMatches(attributeQualifier, tempCurrentPart)) { - if (insideBrackets) { - autoSuggests.add(attributeQualifier); - } - else { - //Dont add already used attribute - if (!lineWithoutCommand.contains(attributeQualifier + ";") - && !lineWithoutCommand.contains(";" + attributeQualifier) - || currentPart.endsWith("(")) { - autoSuggests.add(attributeQualifier); - } - } - } - } - } - } - - boolean includeEquals = true; - boolean includesComma = false; - if (showKeywords) { - if (currentPart.isEmpty() || currentPart.endsWith("[") || currentPart.endsWith(",")) { - if (currentPart.endsWith(",")) { - includesComma = true; - //already have 1, filter the list - autoSuggests = new ArrayList<>(); - String keywordName = currentPart.substring(currentPart.indexOf("[") + 1, currentPart.lastIndexOf("=")); - for (String keyword : Formatter.IMPEX_KEYWORDS_ATTRIBUTES) { - if (!keyword.equalsIgnoreCase(keywordName)) { - autoSuggests.add(keyword); - } - } - } - else { - autoSuggests = Formatter.IMPEX_KEYWORDS_ATTRIBUTES; - } - } - else if (currentPart.trim().endsWith("=")) { - if (currentPart.contains(",")) { - includesComma = true; - } - //code[unique= - String keywordName = ""; - if (includesComma) { - keywordName = currentPart.substring(currentPart.lastIndexOf(",") + 1, currentPart.lastIndexOf("=")); - } - else { - keywordName = currentPart.substring(currentPart.indexOf("[") + 1, currentPart.indexOf("=")); - } - if (keywordName.equalsIgnoreCase("mode")) { - autoSuggests = Lists.newArrayList("append", "remove"); - includeEquals = false; - } - else { - if (Formatter.IMPEX_KEYWORDS_ATTRIBUTES_BOOLEAN.contains(keywordName)) { - autoSuggests = Lists.newArrayList("true", "false"); - includeEquals = false; - } - } - } - else { - //If not empty, filter based on currentPart - autoSuggests = new ArrayList<>(); - for (String keyword : Formatter.IMPEX_KEYWORDS_ATTRIBUTES) { - if (StringHelper.findMatches(keyword, currentPart)) { - autoSuggests.add(keyword); - } - } - } - } - - ICompletionProposal[] autoCompProposals = null; - - if (autoSuggests != null && autoSuggests.size() > 0) { - Collections.sort(autoSuggests); - - if (showTypes) - autoCompProposals = typeProposals(cursorPosition, autoSuggests, currentPart); - if (showAttributes) - autoCompProposals = attributeProposals(cursorPosition, autoSuggests, currentPart); - if (showKeywords) - autoCompProposals = keywordProposals(cursorPosition, autoSuggests, currentPart, includeEquals, includesComma); - exMsg = null; - } - - return autoCompProposals; - } - catch (BadLocationException ble) { - Activator.logError("BadLocationException", ble); - exMsg = ble.getMessage(); - return null; - } - } - - private ICompletionProposal[] typeProposals(int cursorPosition, List autoSuggests, String currentPart) { - - int counter = 0; - ICompletionProposal[] proposals = new ICompletionProposal[autoSuggests.size()]; - for (Iterator iter = autoSuggests.iterator(); iter.hasNext();) { - String autoSuggest = (String)iter.next(); - //Each proposal contains the text to propose, as well as information about where to insert the text into the document. - proposals[counter] = new CompletionProposal(autoSuggest + ";", cursorPosition - currentPart.length(), currentPart.length(), autoSuggest.length() + 1); - counter++; - } - return proposals; - } - - private ICompletionProposal[] attributeProposals(int cursorPosition, List autoSuggests, String currentPart) { - - int counter = 0; - ICompletionProposal[] proposals = new ICompletionProposal[autoSuggests.size()]; - for (Iterator iter = autoSuggests.iterator(); iter.hasNext();) { - String autoSuggest = (String)iter.next(); - - if (currentPart.endsWith(";") || currentPart.endsWith("(")) { - proposals[counter] = new CompletionProposal(autoSuggest, cursorPosition, 0, autoSuggest.length()); - } - else { - int bracketStart = currentPart.indexOf("("); - if (bracketStart > 0) { - int a = (cursorPosition + 1) - (currentPart.length() - bracketStart); - int b = currentPart.length() - (bracketStart + 1); - int c = autoSuggest.length(); - proposals[counter] = new CompletionProposal(autoSuggest, a, b, c); - } - else { - proposals[counter] = new CompletionProposal(autoSuggest, cursorPosition - currentPart.length(), currentPart.length(), autoSuggest.length()); - } - } - counter++; - } - return proposals; - } - - private ICompletionProposal[] keywordProposals(int cursorPosition, List autoSuggests, String currentPart, boolean includeEquals, boolean includesComma) { - - int counter = 0; - ICompletionProposal[] proposals = new ICompletionProposal[autoSuggests.size()]; - for (Iterator iter = autoSuggests.iterator(); iter.hasNext();) { - String autoSuggest = (String)iter.next(); - - if (currentPart.endsWith("[")) { - proposals[counter] = new CompletionProposal(autoSuggest + "=", cursorPosition, 0, autoSuggest.length() + 1); - } - else { - if (includeEquals) { - if (includesComma) { - proposals[counter] = new CompletionProposal(autoSuggest + "=", cursorPosition, 0, autoSuggest.length() + 1); - } - else { - proposals[counter] = new CompletionProposal(autoSuggest + "=", cursorPosition - currentPart.length(), currentPart.length(), autoSuggest.length() + 1); - } - } - else if (includesComma) { - if (currentPart.endsWith("=")) { - proposals[counter] = new CompletionProposal(autoSuggest, cursorPosition, 0, autoSuggest.length()); - } - else { - proposals[counter] = new CompletionProposal(autoSuggest, cursorPosition - currentPart.length(), currentPart.length(), autoSuggest.length() + 1); - } - } - else { - proposals[counter] = new CompletionProposal(autoSuggest, cursorPosition, 0, autoSuggest.length()); - } - } - counter++; - } - return proposals; - } - - @Override - public IContextInformation[] computeContextInformation(ITextViewer textViewer, int cursorPosition) { - exMsg = "No Context Information available"; - return null; - } - - @Override - public char[] getCompletionProposalAutoActivationCharacters() { - - return null; - } - - @Override - public char[] getContextInformationAutoActivationCharacters() { - - return null; - } - - @Override - public IContextInformationValidator getContextInformationValidator() { - return iciv; - } - - @Override - public String getErrorMessage() { - return exMsg; - } - -} diff --git a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/editors/ColorProvider.java b/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/editors/ColorProvider.java deleted file mode 100755 index 038a5d03..00000000 --- a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/editors/ColorProvider.java +++ /dev/null @@ -1,108 +0,0 @@ -/******************************************************************************* - * Copyright 2020 SAP - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy - * of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - ******************************************************************************/ -package com.hybris.impexformatter.editors; - -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.regex.PatternSyntaxException; - -import org.eclipse.swt.graphics.Color; -import org.eclipse.swt.graphics.RGB; -import org.eclipse.swt.widgets.Display; - -import com.google.common.collect.Maps; - -public class ColorProvider { - - private static class ColorProviderHolder { - private final static ColorProvider instance = new ColorProvider(); - } - - public static ColorProvider getInstance() { - return ColorProviderHolder.instance; - } - - private ColorProvider() { - rgbPattern = Pattern.compile(pattern); - } - - - public static final RGB BLUE_COLOR = new RGB(0, 0, 255); - public static final RGB GREY_COLOR = new RGB(192, 192, 192); - public static final RGB DGREY_COLOR = new RGB(180, 180, 180); - public static final RGB ORANGE_COLOR = new RGB(255, 128, 0); - public static final RGB PURPLE_COLOR = new RGB(163, 73, 164); - public static final RGB RED_COLOR = new RGB(204, 0, 0); - public static final RGB BLACK_COLOR = new RGB(0, 0, 0); - public static final String pattern = "RGB \\{([0-9]{1,3}),[ ]?([0-9]{1,3}),[ ]?([0-9]{1,3})\\}"; - public static final RGB GREEN_COLOR = new RGB(0, 255, 0); - - - protected Map fColorTable = new HashMap<>(10); - protected Map fRgbMap = Maps.newHashMap(); - - private Pattern rgbPattern; - - - public void dispose() { - Iterator e = fColorTable.values().iterator(); - while (e.hasNext()) - ((Color) e.next()).dispose(); - } - - public Color getColor(RGB rgb) { - Color color = (Color) fColorTable.get(rgb); - if (color == null) { - color = new Color(Display.getCurrent(), rgb); - fColorTable.put(rgb, color); - } - return color; - } - - - /** - * if string is in format "RGB {255,255,255}" will be transformed to {@code Color} object. - * @param serialFormat - * @return color object - */ - public Color getColor(String serialFormat) { - Matcher matcher = rgbPattern.matcher(serialFormat); - if (!matcher.matches()) { - throw new PatternSyntaxException("serial format is in wrong format " + serialFormat, pattern, 0); - } - Integer red = Integer.valueOf(matcher.group(1)); - Integer green = Integer.valueOf(matcher.group(2)); - Integer blue = Integer.valueOf(matcher.group(3)); - RGB rgb = new RGB(red, green, blue); - return getColor(rgb); - } - - /** - * if parameters contain color value then method return {@inheritDoc Color} object. - * @param r red value for RGB color - * @param g green value for RGB color - * @param b blue value for RGB color - * - * @return color object - */ - public Color getColor(final int r, final int g,final int b) { - RGB rgb = new RGB(r, g, b); - return getColor(rgb); - } -} diff --git a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/editors/ImpexEditor.java b/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/editors/ImpexEditor.java deleted file mode 100755 index 39871645..00000000 --- a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/editors/ImpexEditor.java +++ /dev/null @@ -1,51 +0,0 @@ -/******************************************************************************* - * Copyright 2020 SAP - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy - * of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - ******************************************************************************/ -package com.hybris.impexformatter.editors; - -//import org.eclipse.jface.text.source.AnnotationRulerColumn; -//import org.eclipse.jface.text.source.CompositeRuler; -//import org.eclipse.jface.text.source.IVerticalRuler; -import org.eclipse.ui.editors.text.TextEditor; - -import com.hybris.impexformatter.Activator; -import com.hybris.impexformatter.DocumentProvider; - -public class ImpexEditor extends TextEditor { - - public ImpexEditor() { - super(); - setSourceViewerConfiguration(new ImpexSourceViewerConfig(getPreferenceStore())); - setDocumentProvider(new DocumentProvider()); - } - - /** Keeps the legacy formatter shortcut local to this editor during migration. */ - @Override - protected void initializeKeyBindingScopes() { - setKeyBindingScopes(new String[] {Activator.EDITOR_CONTEXT_ID}); - } - - /*@Override - protected IVerticalRuler createVerticalRuler() { - int rulerWidth = 10; - CompositeRuler ruler = new CompositeRuler(); - ruler.addDecorator(0, new AnnotationRulerColumn(rulerWidth)); - if (isLineNumberRulerVisible()) { - ruler.addDecorator(1, createLineNumberRulerColumn()); - } - return ruler; - }*/ - -} diff --git a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/editors/ImpexFormatAction.java b/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/editors/ImpexFormatAction.java deleted file mode 100755 index 2c56ddba..00000000 --- a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/editors/ImpexFormatAction.java +++ /dev/null @@ -1,49 +0,0 @@ -/******************************************************************************* - * Copyright 2020 SAP - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy - * of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - ******************************************************************************/ -package com.hybris.impexformatter.editors; - -import org.eclipse.jface.action.IAction; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.ui.IEditorActionDelegate; -import org.eclipse.ui.IEditorPart; - -/** - * Action responsible for formatting impex file - * @author SAP - * - */ -public class ImpexFormatAction implements IEditorActionDelegate { - - private IEditorPart editorPart = null; - - @Override - public void run(IAction arg0) { - if(editorPart != null) { - ImpexPageEditor.formatText(editorPart); - } - } - - @Override - public void selectionChanged(IAction arg0, ISelection arg1) { - - } - - @Override - public void setActiveEditor(IAction arg0, IEditorPart arg1) { - this.editorPart = arg1; - } - -} diff --git a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/editors/ImpexPageEditor.java b/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/editors/ImpexPageEditor.java deleted file mode 100755 index a1d18601..00000000 --- a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/editors/ImpexPageEditor.java +++ /dev/null @@ -1,183 +0,0 @@ -/******************************************************************************* - * Copyright 2020 SAP - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy - * of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - ******************************************************************************/ -package com.hybris.impexformatter.editors; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.StringReader; -import java.io.StringWriter; -import java.util.Locale; - -import org.eclipse.core.resources.IMarker; -import org.eclipse.core.resources.IResourceChangeEvent; -import org.eclipse.core.resources.IResourceChangeListener; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.jface.dialogs.ErrorDialog; -import org.eclipse.swt.widgets.Display; -import org.eclipse.ui.IEditorInput; -import org.eclipse.ui.IEditorPart; -import org.eclipse.ui.IEditorSite; -import org.eclipse.ui.IFileEditorInput; -import org.eclipse.ui.IWorkbenchPage; -import org.eclipse.ui.PartInitException; -import org.eclipse.ui.ide.IDE; -import org.eclipse.ui.part.FileEditorInput; -import org.eclipse.ui.part.MultiPageEditorPart; - -import com.hybris.impexformatter.Activator; -import com.hybris.impexformatter.actions.Formatter; - -/** - * An example showing how to create a multi-page editor. This example has 3 pages: - *
    - *
  • page 0 contains a nested text editor. - *
  • page 1 allows you to change the font used in page 2 - *
  • page 2 shows the words in page 0 in sorted order - *
- */ -public class ImpexPageEditor extends MultiPageEditorPart implements IResourceChangeListener { - - /** The text editor used in page 0. */ - private ImpexEditor editor; - - /** - * Creates a multi-page editor example. - */ - public ImpexPageEditor() { - super(); - ResourcesPlugin.getWorkspace().addResourceChangeListener(this); - } - - /** - * The MultiPageEditorPart implementation of this IWorkbenchPart method disposes all - * nested editors. Subclasses may extend. - */ - public void dispose() { - ResourcesPlugin.getWorkspace().removeResourceChangeListener(this); - super.dispose(); - } - - /** - * Saves the multi-page editor's document. - */ - public void doSave(IProgressMonitor monitor) { - getEditor(0).doSave(monitor); - } - - /** - * Saves the multi-page editor's document as another file. Also updates the text for page 0's tab, and updates this - * multi-page editor's input to correspond to the nested editor's. - */ - public void doSaveAs() { - IEditorPart editor = getEditor(0); - editor.doSaveAs(); - setPageText(0, editor.getTitle()); - setInput(editor.getEditorInput()); - } - - /* - * (non-Javadoc) Method declared on IEditorPart - */ - public void gotoMarker(IMarker marker) { - setActivePage(0); - IDE.gotoMarker(getEditor(0), marker); - } - - /** - * The MultiPageEditorExample implementation of this method checks that the input is an instance of - * IFileEditorInput. - */ - public void init(IEditorSite site, IEditorInput editorInput) throws PartInitException { - if (!(editorInput instanceof IFileEditorInput)) - throw new PartInitException("Invalid Input: Must be IFileEditorInput"); - super.init(site, editorInput); - } - - /* - * (non-Javadoc) Method declared on IEditorPart. - */ - public boolean isSaveAsAllowed() { - return true; - } - - /** - * Closes all project files on project close. - */ - public void resourceChanged(final IResourceChangeEvent event) { - if (event.getType() == IResourceChangeEvent.PRE_CLOSE) { - Display.getDefault().asyncExec(new Runnable() { - public void run() { - IWorkbenchPage[] pages = getSite().getWorkbenchWindow().getPages(); - for (int i = 0; i < pages.length; i++) { - if (((FileEditorInput) editor.getEditorInput()).getFile().getProject() - .equals(event.getResource())) { - IEditorPart editorPart = pages[i].findEditor(editor.getEditorInput()); - pages[i].closeEditor(editorPart, true); - } - } - } - }); - } - } - - static void formatText(IEditorPart editorPart) { - if(editorPart instanceof ImpexPageEditor pageEditor) { - String unformattedText = pageEditor.editor.getDocumentProvider().getDocument(editorPart.getEditorInput()).get(); - - try (BufferedReader reader = new BufferedReader(new StringReader(unformattedText)); - StringWriter writer = new StringWriter()) { - String line = null; - while ((line = reader.readLine()) != null) { - while (line.toUpperCase(Locale.ENGLISH).matches(Formatter.HEADER_MODE)) { - // start of new block - line = Formatter.formatData(reader, writer, line); - if (line == null) { - break; - } - } - if (line != null) { - writer.append(line); - writer.write(System.getProperty(Formatter.LINE_SEPARATOR)); - } - } - - pageEditor.editor.getDocumentProvider().getDocument(editorPart.getEditorInput()).set(writer.toString()); - - } - catch (final IOException e) { - Activator.logError("IOException", e); - } - } - } - - protected void createPages() { - createPage0(); - } - - void createPage0() { - try { - editor = new ImpexEditor(); - int index = addPage(editor, getEditorInput()); - setPageText(index, editor.getTitle()); - setPartName(editor.getTitle()); - - } - catch (PartInitException e) { - ErrorDialog.openError(getSite().getShell(), "Error creating nested text editor", null, e.getStatus()); - } - } -} diff --git a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/editors/ImpexSourceViewerConfig.java b/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/editors/ImpexSourceViewerConfig.java deleted file mode 100755 index bcab5ce4..00000000 --- a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/editors/ImpexSourceViewerConfig.java +++ /dev/null @@ -1,150 +0,0 @@ -/******************************************************************************* - * Copyright 2020 SAP - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy - * of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - ******************************************************************************/ -package com.hybris.impexformatter.editors; - -import java.util.HashMap; -import java.util.Map; - -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.text.DefaultIndentLineAutoEditStrategy; -import org.eclipse.jface.text.IAutoEditStrategy; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.contentassist.ContentAssistant; -import org.eclipse.jface.text.contentassist.IContentAssistProcessor; -import org.eclipse.jface.text.contentassist.IContentAssistant; -import org.eclipse.jface.text.hyperlink.IHyperlinkDetector; -import org.eclipse.jface.text.presentation.IPresentationReconciler; -import org.eclipse.jface.text.presentation.PresentationReconciler; -import org.eclipse.jface.text.rules.DefaultDamagerRepairer; -import org.eclipse.jface.text.rules.RuleBasedScanner; -import org.eclipse.jface.text.source.ISourceViewer; -import org.eclipse.ui.editors.text.TextSourceViewerConfiguration; - -import com.hybris.impexformatter.Activator; -import com.hybris.impexformatter.ImpexDocumentPartitioner; -import com.hybris.impexformatter.assistprocessors.ImpexCommandContentAssistProcessor; -import com.hybris.impexformatter.assistprocessors.ImpexCommentContentAssistProcessor; -import com.hybris.impexformatter.assistprocessors.ImpexDataContentAssistProcessor; -import com.hybris.impexformatter.assistprocessors.ImpexInstructionContentAssistProcessor; -import com.hybris.impexformatter.assistprocessors.ImpexTypeSystemContentAssistProcessor; -import com.hybris.impexformatter.hyperlink.ImpexTypeHyperlinkDetector; -import com.hybris.impexformatter.scanners.ImpexBracesAutoEditStrategy; -import com.hybris.impexformatter.scanners.ImpexRuleScanner; -import com.hybris.impexformatter.scanners.InstructionsRuleScanner; - -public class ImpexSourceViewerConfig extends TextSourceViewerConfiguration { - - Map scanMap = new HashMap<>(); - - public ImpexSourceViewerConfig(IPreferenceStore preferenceStore) { - - super(preferenceStore); - } - - @Override - public IHyperlinkDetector[] getHyperlinkDetectors(ISourceViewer sourceViewer) { - - return new IHyperlinkDetector[]{new ImpexTypeHyperlinkDetector()}; - } - - public IPresentationReconciler getPresentationReconciler(ISourceViewer sourceViewer) { - - PresentationReconciler reconciler = new PresentationReconciler(); - DefaultDamagerRepairer dr = new DefaultDamagerRepairer(getImpexScanner(ImpexDocumentPartitioner.IMPEX_INSTRUCTION)); - reconciler.setDamager(dr, ImpexDocumentPartitioner.IMPEX_INSTRUCTION); - reconciler.setRepairer(dr, ImpexDocumentPartitioner.IMPEX_INSTRUCTION); - dr = new DefaultDamagerRepairer(getImpexScanner(null)); - reconciler.setDamager(dr, IDocument.DEFAULT_CONTENT_TYPE); - reconciler.setRepairer(dr, IDocument.DEFAULT_CONTENT_TYPE); - return reconciler; - } - - @Override - public String getConfiguredDocumentPartitioning(ISourceViewer sourceViewer) { - - return Activator.IMPEX_PARTITIONING; - } - - @Override - public String[] getConfiguredContentTypes(ISourceViewer sourceViewer) { - - return new String[] { - IDocument.DEFAULT_CONTENT_TYPE, - ImpexDocumentPartitioner.IMPEX_COMMENT, - ImpexDocumentPartitioner.IMPEX_DATA, - ImpexDocumentPartitioner.IMPEX_HEADER, - ImpexDocumentPartitioner.IMPEX_INSTRUCTION }; - } - - @Override - public IAutoEditStrategy[] getAutoEditStrategies(ISourceViewer sourceViewer, String contentType) { - - IAutoEditStrategy strategy= (IDocument.DEFAULT_CONTENT_TYPE.equalsIgnoreCase(contentType) ? new ImpexBracesAutoEditStrategy() : new DefaultIndentLineAutoEditStrategy()); - - IAutoEditStrategy headerStr = (ImpexDocumentPartitioner.IMPEX_HEADER.equalsIgnoreCase(contentType) ? new ImpexBracesAutoEditStrategy() : new DefaultIndentLineAutoEditStrategy()); - - return new IAutoEditStrategy[] { strategy, headerStr }; - } - - @Override - public IContentAssistant getContentAssistant(ISourceViewer sourceViewer) { - - ContentAssistant assistant = new ContentAssistant(); - assistant.enableAutoActivation(true); - assistant.setAutoActivationDelay(300); - assistant.setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer)); - assistant.setProposalPopupOrientation(IContentAssistant.PROPOSAL_OVERLAY); - assistant.enableAutoInsert(true); - assistant.enablePrefixCompletion(true); - - IContentAssistProcessor pr = new ImpexInstructionContentAssistProcessor(); - assistant.setContentAssistProcessor(pr, ImpexDocumentPartitioner.IMPEX_INSTRUCTION); - - //pr = new ImpexTypeAttributeContentAssistProcessor(); - pr = new ImpexTypeSystemContentAssistProcessor(); - assistant.setContentAssistProcessor(pr, ImpexDocumentPartitioner.IMPEX_HEADER); - - pr = new ImpexDataContentAssistProcessor(); - assistant.setContentAssistProcessor(pr, ImpexDocumentPartitioner.IMPEX_DATA); - - pr = new ImpexCommentContentAssistProcessor(); - assistant.setContentAssistProcessor(pr, ImpexDocumentPartitioner.IMPEX_COMMENT); - - pr = new ImpexCommandContentAssistProcessor(); - assistant.setContentAssistProcessor(pr, IDocument.DEFAULT_CONTENT_TYPE); - - assistant.setInformationControlCreator(getInformationControlCreator(sourceViewer)); - return assistant; - } - - protected RuleBasedScanner getImpexScanner(String partition) { - - RuleBasedScanner scanner = scanMap.get(partition); - if (scanner == null) { - scanner = new ImpexRuleScanner(ColorProvider.getInstance()); - if (partition != null) { - switch (partition) { - case ImpexDocumentPartitioner.IMPEX_INSTRUCTION: - scanner = new InstructionsRuleScanner(ColorProvider.getInstance()); - break; - } - } - - } - return scanner; - } - -} diff --git a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/editors/MultiPageEditorContributor.java b/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/editors/MultiPageEditorContributor.java deleted file mode 100755 index df86659a..00000000 --- a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/editors/MultiPageEditorContributor.java +++ /dev/null @@ -1,104 +0,0 @@ -/******************************************************************************* - * Copyright 2020 SAP - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy - * of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - ******************************************************************************/ -package com.hybris.impexformatter.editors; - -import org.eclipse.jface.action.IAction; -import org.eclipse.jface.action.IMenuManager; -import org.eclipse.jface.action.IToolBarManager; -import org.eclipse.jface.action.MenuManager; -import org.eclipse.jface.action.Separator; -import org.eclipse.ui.IActionBars; -import org.eclipse.ui.IEditorPart; -import org.eclipse.ui.IWorkbenchActionConstants; -import org.eclipse.ui.actions.ActionFactory; -import org.eclipse.ui.ide.IDEActionFactory; -import org.eclipse.ui.part.MultiPageEditorActionBarContributor; -import org.eclipse.ui.texteditor.ITextEditor; -import org.eclipse.ui.texteditor.ITextEditorActionConstants; - -/** - * Manages the installation/deinstallation of global actions for page editor. Responsible for the redirection of global - * actions to the active editor. Page contributor replaces the contributors for the individual editors in the page - * editor. - */ -public class MultiPageEditorContributor extends MultiPageEditorActionBarContributor { - private IEditorPart activeEditorPart; - - /** - * Creates a multi-page contributor. - */ - public MultiPageEditorContributor() { - super(); - } - - /** - * Returns the action registed with the given text editor. - * - * @return IAction or null if editor is null. - */ - protected IAction getAction(ITextEditor editor, String actionID) { - return (editor == null ? null : editor.getAction(actionID)); - } - - /* - * (non-JavaDoc) Method declared in AbstractMultiPageEditorActionBarContributor. - */ - - public void setActivePage(IEditorPart part) { - if (activeEditorPart == part) - return; - - activeEditorPart = part; - - IActionBars actionBars = getActionBars(); - if (actionBars != null) { - ITextEditor editor = (part instanceof ITextEditor ite) ? ite : null; - - actionBars.setGlobalActionHandler(ActionFactory.DELETE.getId(), - getAction(editor, ITextEditorActionConstants.DELETE)); - actionBars.setGlobalActionHandler(ActionFactory.UNDO.getId(), - getAction(editor, ITextEditorActionConstants.UNDO)); - actionBars.setGlobalActionHandler(ActionFactory.REDO.getId(), - getAction(editor, ITextEditorActionConstants.REDO)); - actionBars.setGlobalActionHandler(ActionFactory.CUT.getId(), - getAction(editor, ITextEditorActionConstants.CUT)); - actionBars.setGlobalActionHandler(ActionFactory.COPY.getId(), - getAction(editor, ITextEditorActionConstants.COPY)); - actionBars.setGlobalActionHandler(ActionFactory.PASTE.getId(), - getAction(editor, ITextEditorActionConstants.PASTE)); - actionBars.setGlobalActionHandler(ActionFactory.SELECT_ALL.getId(), - getAction(editor, ITextEditorActionConstants.SELECT_ALL)); - actionBars.setGlobalActionHandler(ActionFactory.FIND.getId(), - getAction(editor, ITextEditorActionConstants.FIND)); - actionBars.setGlobalActionHandler(IDEActionFactory.BOOKMARK.getId(), - getAction(editor, IDEActionFactory.BOOKMARK.getId())); - actionBars.updateActionBars(); - - } - } - - public void contributeToMenu(IMenuManager manager) { - - IMenuManager menu = new MenuManager("Editor &Menu"); - manager.prependToGroup(IWorkbenchActionConstants.MB_ADDITIONS, menu); - } - - public void contributeToToolBar(IToolBarManager manager) { - - manager.add(new Separator()); - } - -} diff --git a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/handlers/NewImpexWizardHandler.java b/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/handlers/NewImpexWizardHandler.java deleted file mode 100644 index e9ac08ae..00000000 --- a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/handlers/NewImpexWizardHandler.java +++ /dev/null @@ -1,43 +0,0 @@ -/******************************************************************************* - * Copyright 2020 SAP - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy - * of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - ******************************************************************************/ -package com.hybris.impexformatter.handlers; - -import org.eclipse.core.commands.AbstractHandler; -import org.eclipse.core.commands.ExecutionEvent; -import org.eclipse.core.commands.ExecutionException; -import org.eclipse.jface.wizard.IWizard; -import org.eclipse.jface.wizard.WizardDialog; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.ui.handlers.HandlerUtil; - -import com.hybris.impexformatter.wizards.NewImpexWizard; - -public class NewImpexWizardHandler extends AbstractHandler { - - @Override - public Object execute( ExecutionEvent event ) throws ExecutionException - { - Shell activeShell = HandlerUtil.getActiveShell(event); - NewImpexWizard newWizard = new NewImpexWizard(); - newWizard.setCurrentSelection(HandlerUtil.getCurrentSelection(event)); - - IWizard wizard = (IWizard) newWizard; - WizardDialog dialog = new WizardDialog(activeShell, wizard); - dialog.open(); - return null; - } - -} diff --git a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/hyperlink/ImpexTypeHyperlink.java b/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/hyperlink/ImpexTypeHyperlink.java deleted file mode 100644 index 7ba31bce..00000000 --- a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/hyperlink/ImpexTypeHyperlink.java +++ /dev/null @@ -1,84 +0,0 @@ -/******************************************************************************* - * Copyright 2020 SAP - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy - * of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - ******************************************************************************/ -package com.hybris.impexformatter.hyperlink; - -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IMarker; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.Path; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.hyperlink.IHyperlink; -import org.eclipse.ui.IWorkbenchPage; -import org.eclipse.ui.PlatformUI; -import org.eclipse.ui.ide.IDE; - -import com.hybris.hyeclipse.commons.typesystem.YType; -import com.hybris.impexformatter.Activator; - -public class ImpexTypeHyperlink implements IHyperlink { - - private final IRegion fUrlRegion; - private String location; - - public ImpexTypeHyperlink(IRegion targetRegion, String text) { - fUrlRegion = targetRegion; - location = text; - } - - @Override - public IRegion getHyperlinkRegion() { - return fUrlRegion; - } - - @Override - public String getHyperlinkText() { - - return null; - } - - @Override - public String getTypeLabel() { - - return null; - } - - @Override - public void open() { - IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); - - final YType type = Activator.getDefault().getTypeSystemSnapshot().getType(location); - if (type == null || page == null) { - return; - } - final IFile source = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(type.getSourcePath())); - if (!source.exists()) { - return; - } - try { - final IMarker marker = source.createMarker(IMarker.TEXT); - try { - marker.setAttribute(IMarker.LINE_NUMBER, type.getSourceLine()); - IDE.openEditor(page, marker); - } finally { - marker.delete(); - } - } catch (CoreException e) { - Activator.logError("Could not open generated model source", e); - } - } - -} diff --git a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/hyperlink/ImpexTypeHyperlinkDetector.java b/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/hyperlink/ImpexTypeHyperlinkDetector.java deleted file mode 100644 index 51d55dd8..00000000 --- a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/hyperlink/ImpexTypeHyperlinkDetector.java +++ /dev/null @@ -1,84 +0,0 @@ -/******************************************************************************* - * Copyright 2020 SAP - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy - * of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - ******************************************************************************/ -package com.hybris.impexformatter.hyperlink; - -import java.util.List; -import java.util.Locale; - -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.ITextViewer; -import org.eclipse.jface.text.Region; -import org.eclipse.jface.text.hyperlink.AbstractHyperlinkDetector; -import org.eclipse.jface.text.hyperlink.IHyperlink; -import org.eclipse.jface.text.hyperlink.IHyperlinkDetector; - -import com.hybris.impexformatter.Activator; - -public class ImpexTypeHyperlinkDetector extends AbstractHyperlinkDetector implements IHyperlinkDetector { - - - @Override - public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region, boolean canShowMultipleHyperlinks) { - - IDocument document = textViewer.getDocument(); - int offset = region.getOffset(); - - // extract relevant characters - IRegion lineRegion; - String candidate; - try { - lineRegion = document.getLineInformationOfOffset(offset); - candidate = document.get(lineRegion.getOffset(), lineRegion.getLength()); - } - catch (BadLocationException ex) { - return null; - } - - String upperCandidate = candidate.toUpperCase(Locale.ENGLISH); - if (upperCandidate.startsWith("INSERT") || upperCandidate.startsWith("REMOVE") || upperCandidate.startsWith("UPDATE")) { - // look for keyword - final List allTypeNames = Activator.getDefault().getAllTypeNames(); - if (candidate.indexOf(";") < 0) { - return null; - } - - String headerPlusType = candidate.substring(0, candidate.indexOf(";")); - String typeName = headerPlusType.substring(candidate.indexOf(" ") + 1, headerPlusType.length()); - if (allTypeNames.contains(typeName)) { - - int index = candidate.indexOf(typeName); - if (index != -1) { - - // detect region containing keyword - IRegion targetRegion = new Region(lineRegion.getOffset() + index, typeName.length()); - if ((targetRegion.getOffset() <= offset) && ((targetRegion.getOffset() + targetRegion.getLength()) > offset)) { - try { - return new IHyperlink[] { new ImpexTypeHyperlink(targetRegion, document.get(targetRegion.getOffset(), targetRegion.getLength())) }; - } - catch (BadLocationException e) { - Activator.logError("BadLocationException", e); - } - } - } - } - } - - return null; - } - -} diff --git a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/preferences/ImpexPreferencePage.java b/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/preferences/ImpexPreferencePage.java deleted file mode 100755 index a7edf027..00000000 --- a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/preferences/ImpexPreferencePage.java +++ /dev/null @@ -1,75 +0,0 @@ -/******************************************************************************* - * Copyright 2020 SAP - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy - * of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - ******************************************************************************/ -package com.hybris.impexformatter.preferences; - -import org.eclipse.jface.preference.ColorFieldEditor; -import org.eclipse.jface.preference.FieldEditorPreferencePage; -import org.eclipse.ui.IWorkbench; -import org.eclipse.ui.IWorkbenchPreferencePage; - -import com.hybris.impexformatter.Activator; - -/** - * This class represents a preference page that - * is contributed to the Preferences dialog. By - * subclassing FieldEditorPreferencePage, we - * can use the field support built into JFace that allows - * us to create a page that is small and knows how to - * save, restore and apply itself. - *

- * This page is used to modify preferences only. They - * are stored in the preference store that belongs to - * the main plug-in class. That way, preferences can - * be accessed directly via the preference store. - */ - -public class ImpexPreferencePage - extends FieldEditorPreferencePage - implements IWorkbenchPreferencePage { - - public ImpexPreferencePage() { - super(GRID); - setPreferenceStore(Activator.getDefault().getPreferenceStore()); - setDescription("Colours"); - } - - /** - * Creates the field editors. Field editors are abstractions of - * the common GUI blocks needed to manipulate various types - * of preferences. Each field editor knows how to save and - * restore itself. - */ - public void createFieldEditors() { - - addField(new ColorFieldEditor(PreferenceConstants.P_COMMENT_COLOR, "Comments: ", getFieldEditorParent())); - addField(new ColorFieldEditor(PreferenceConstants.P_DEF_COLOR, "Variables ($productCatalog, $languages,...): ", getFieldEditorParent())); - addField(new ColorFieldEditor(PreferenceConstants.P_TAG_COLOR, "Tags (INSERT, INSERT_UPDATE,...: ", getFieldEditorParent())); - addField(new ColorFieldEditor(PreferenceConstants.P_INSTRUCT_COLOR, "Instructions: ", getFieldEditorParent())); - addField(new ColorFieldEditor(PreferenceConstants.P_MODIF_COLOR, "Modifiers (unique, default,...: ", getFieldEditorParent())); - addField(new ColorFieldEditor(PreferenceConstants.P_KVAL_COLOR, "Keywords (true, false,...: ", getFieldEditorParent())); - addField(new ColorFieldEditor(PreferenceConstants.P_REF_COLOR, "References: ", getFieldEditorParent())); - addField(new ColorFieldEditor(PreferenceConstants.P_STRING_COLOR, "Main Text: ", getFieldEditorParent())); - - } - - /* (non-Javadoc) - * @see org.eclipse.ui.IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench) - */ - public void init(IWorkbench workbench) { - - } - -} diff --git a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/preferences/PreferenceConstants.java b/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/preferences/PreferenceConstants.java deleted file mode 100755 index 84e634a1..00000000 --- a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/preferences/PreferenceConstants.java +++ /dev/null @@ -1,33 +0,0 @@ -/******************************************************************************* - * Copyright 2020 SAP - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy - * of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - ******************************************************************************/ -package com.hybris.impexformatter.preferences; - - -/** - * Constant definitions for plug-in preferences - */ -public class PreferenceConstants { - - public static final String P_STRING_COLOR = "impexStringColorPreference"; - public static final String P_COMMENT_COLOR = "impexCommentColorPreference"; - public static final String P_INSTRUCT_COLOR = "impexInstructColorPreference"; - public static final String P_MODIF_COLOR = "impexModifColorPreference"; - public static final String P_TAG_COLOR = "impexTagColorPreference"; - public static final String P_KVAL_COLOR = "impexKvalColorPreference"; - public static final String P_REF_COLOR = "impexReferenceColorPreference"; - public static final String P_DEF_COLOR = "impexDefColorPreference"; - -} diff --git a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/preferences/PreferenceInitializer.java b/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/preferences/PreferenceInitializer.java deleted file mode 100755 index 8e3fccdc..00000000 --- a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/preferences/PreferenceInitializer.java +++ /dev/null @@ -1,49 +0,0 @@ -/******************************************************************************* - * Copyright 2020 SAP - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy - * of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - ******************************************************************************/ -package com.hybris.impexformatter.preferences; - -import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer; -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.preference.PreferenceConverter; - -import com.hybris.impexformatter.Activator; -import com.hybris.impexformatter.editors.ColorProvider; - -/** - * Class used to initialize default preference values. - */ -public class PreferenceInitializer extends AbstractPreferenceInitializer { - - /* - * (non-Javadoc) - * - * @see org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer#initializeDefaultPreferences() - */ - public void initializeDefaultPreferences() { - IPreferenceStore store = Activator.getDefault().getPreferenceStore(); - - PreferenceConverter.setDefault(store, PreferenceConstants.P_STRING_COLOR, ColorProvider.GREEN_COLOR); - PreferenceConverter.setDefault(store, PreferenceConstants.P_COMMENT_COLOR, ColorProvider.GREY_COLOR); - PreferenceConverter.setDefault(store, PreferenceConstants.P_INSTRUCT_COLOR, ColorProvider.DGREY_COLOR); - PreferenceConverter.setDefault(store, PreferenceConstants.P_MODIF_COLOR, ColorProvider.PURPLE_COLOR); - PreferenceConverter.setDefault(store, PreferenceConstants.P_TAG_COLOR, ColorProvider.PURPLE_COLOR); - PreferenceConverter.setDefault(store, PreferenceConstants.P_KVAL_COLOR, ColorProvider.ORANGE_COLOR); - PreferenceConverter.setDefault(store, PreferenceConstants.P_REF_COLOR, ColorProvider.RED_COLOR); - PreferenceConverter.setDefault(store, PreferenceConstants.P_DEF_COLOR, ColorProvider.BLUE_COLOR); - - } - -} diff --git a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/rules/RuleFactory.java b/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/rules/RuleFactory.java deleted file mode 100755 index 68928595..00000000 --- a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/rules/RuleFactory.java +++ /dev/null @@ -1,79 +0,0 @@ -/******************************************************************************* - * Copyright 2020 SAP - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy - * of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - ******************************************************************************/ -package com.hybris.impexformatter.rules; - -import org.eclipse.jface.text.rules.IToken; -import org.eclipse.jface.text.rules.IWordDetector; -import org.eclipse.jface.text.rules.Token; -import org.eclipse.jface.text.rules.WordRule; - -public class RuleFactory { - - public enum ImpexRules {KEYWORD, VARIABLE, REFERENCE, SEMICOLON, COMMA} - - public static WordRule buildRule(ImpexRules ruleType, IToken token) { - return switch (ruleType) { - case KEYWORD -> buildKeywordRule(token); - case VARIABLE -> buildVariableRule('$', token); - case REFERENCE -> buildVariableRule('&', token); - case SEMICOLON -> buildCharRule(';', token); - case COMMA -> buildCharRule(',', token); - default -> null; - }; - } - - private static WordRule buildCharRule(final char startChar, IToken token) { - if (token == null) {token = Token.UNDEFINED;} - return new WordRule(new IWordDetector() { - - @Override - public boolean isWordStart(char c) { - return c == startChar; - } - - @Override - public boolean isWordPart(char c) { - return false; - } - }, token); - } - - private static WordRule buildKeywordRule(IToken token) { - if (token == null) {token = Token.UNDEFINED;} - return new WordRule(new IWordDetector() { - public boolean isWordStart(char c) { - return Character.isJavaIdentifierStart(c); - } - - public boolean isWordPart(char c) { - return Character.isJavaIdentifierPart(c); - } - }, token); - } - - private static WordRule buildVariableRule(final char startChar, IToken token) { - if (token == null) {token = Token.UNDEFINED;} - return new WordRule(new IWordDetector() { - public boolean isWordStart(char c) { - return c == startChar; - } - - public boolean isWordPart(char c) { - return Character.isJavaIdentifierPart(c); - } - }, token); - } -} diff --git a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/scanners/ImpexBracesAutoEditStrategy.java b/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/scanners/ImpexBracesAutoEditStrategy.java deleted file mode 100755 index af76479a..00000000 --- a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/scanners/ImpexBracesAutoEditStrategy.java +++ /dev/null @@ -1,54 +0,0 @@ -/******************************************************************************* - * Copyright 2020 SAP - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy - * of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - ******************************************************************************/ -package com.hybris.impexformatter.scanners; - -import org.eclipse.jface.text.DocumentCommand; -import org.eclipse.jface.text.IAutoEditStrategy; -import org.eclipse.jface.text.IDocument; - -public class ImpexBracesAutoEditStrategy implements IAutoEditStrategy { - - @Override - public void customizeDocumentCommand(IDocument document, DocumentCommand command) { - - if (command.text.equalsIgnoreCase("\"")) { - command.text = "\"\""; - configureCommand(command); - } - else if (command.text.equalsIgnoreCase("'")) { - command.text = "''"; - configureCommand(command); - } - else if (command.text.equalsIgnoreCase("[")) { - command.text = "[]"; - configureCommand(command); - } - else if (command.text.equalsIgnoreCase("(")) { - command.text = "()"; - configureCommand(command); - } - - } - - private void configureCommand(DocumentCommand command) { - // puts the caret between both the quotes - - command.caretOffset = command.offset + 1; - command.shiftsCaret = false; - - } - -} diff --git a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/scanners/ImpexPartitionScanner.java b/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/scanners/ImpexPartitionScanner.java deleted file mode 100755 index 70cca2d7..00000000 --- a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/scanners/ImpexPartitionScanner.java +++ /dev/null @@ -1,60 +0,0 @@ -/******************************************************************************* - * Copyright 2020 SAP - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy - * of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - ******************************************************************************/ -package com.hybris.impexformatter.scanners; - -//import java.util.ArrayList; -//import java.util.List; - -//import org.eclipse.jface.text.rules.EndOfLineRule; -//import org.eclipse.jface.text.rules.IPredicateRule; -//import org.eclipse.jface.text.rules.IToken; -import org.eclipse.jface.text.rules.RuleBasedPartitionScanner; -//import org.eclipse.jface.text.rules.SingleLineRule; -//import org.eclipse.jface.text.rules.Token; - -public class ImpexPartitionScanner extends RuleBasedPartitionScanner { - - public final static String yIMPEX_DATA = "__y_impex_data"; - public final static String yIMPEX_COMMENT = "__y_impex_comment"; - public final static String yIMPEX_INSTRUCTION = "__y_impex_instruction"; - public final static String yIMPEX_HEADER = "__y_impex_header"; - - public final static String[] yPARTITIONS = new String[] {yIMPEX_DATA, yIMPEX_COMMENT, yIMPEX_INSTRUCTION, yIMPEX_HEADER}; - - public ImpexPartitionScanner() { - - /*super(); - - IToken data = new Token(ImpexPartitionScanner.IMPEX_DATA); - IToken comment = new Token(ImpexPartitionScanner.IMPEX_COMMENT); - IToken instruction = new Token(ImpexPartitionScanner.IMPEX_INSTRUCTION); - IToken header = new Token(ImpexPartitionScanner.IMPEX_HEADER); - - List rules = new ArrayList<>(); - - rules.add(new EndOfLineRule(";", data)); - rules.add(new EndOfLineRule("#", comment)); - rules.add(new EndOfLineRule("#%", instruction)); - rules.add(new SingleLineRule("INSERT", null, header, '\\', true, true)); - rules.add(new SingleLineRule("UPDATE", null, header, '\\', true, true)); - rules.add(new SingleLineRule("REMOVE", null, header, '\\', true, true)); - - IPredicateRule[] result= new IPredicateRule[rules.size()]; - rules.toArray(result); - setPredicateRules(result);*/ - } - -} diff --git a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/scanners/ImpexRuleScanner.java b/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/scanners/ImpexRuleScanner.java deleted file mode 100755 index 0cd9b18d..00000000 --- a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/scanners/ImpexRuleScanner.java +++ /dev/null @@ -1,101 +0,0 @@ -/******************************************************************************* - * Copyright 2020 SAP - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy - * of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - ******************************************************************************/ -package com.hybris.impexformatter.scanners; - -import java.awt.Font; -import java.util.List; - -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.preference.PreferenceConverter; -import org.eclipse.jface.text.TextAttribute; -import org.eclipse.jface.text.rules.EndOfLineRule; -import org.eclipse.jface.text.rules.IRule; -import org.eclipse.jface.text.rules.IToken; -import org.eclipse.jface.text.rules.MultiLineRule; -import org.eclipse.jface.text.rules.RuleBasedScanner; -import org.eclipse.jface.text.rules.Token; -import org.eclipse.jface.text.rules.WordRule; - -import com.google.common.collect.Lists; -import com.hybris.impexformatter.Activator; -import com.hybris.impexformatter.actions.Formatter; -import com.hybris.impexformatter.editors.ColorProvider; -import com.hybris.impexformatter.preferences.PreferenceConstants; -import com.hybris.impexformatter.rules.RuleFactory; -import com.hybris.impexformatter.rules.RuleFactory.ImpexRules; - -/** - * Scanner which contains sequence of rules - */ -public class ImpexRuleScanner extends RuleBasedScanner { - - IPreferenceStore store = Activator.getDefault().getPreferenceStore(); - - public ImpexRuleScanner(ColorProvider provider) { - IToken stringToken = new Token(new TextAttribute(provider.getColor(PreferenceConverter.getColor(store, PreferenceConstants.P_STRING_COLOR)))); - IToken commentToken = new Token(new TextAttribute(provider.getColor(PreferenceConverter.getColor(store, PreferenceConstants.P_COMMENT_COLOR)))); - IToken instructToken = new Token(new TextAttribute(provider.getColor(PreferenceConverter.getColor(store, PreferenceConstants.P_INSTRUCT_COLOR)), null, Font.ITALIC)); - IToken modifiersToken = new Token(new TextAttribute(provider.getColor(PreferenceConverter.getColor(store, PreferenceConstants.P_MODIF_COLOR)))); - IToken impexTagsToken = new Token(new TextAttribute(provider.getColor(PreferenceConverter.getColor(store, PreferenceConstants.P_TAG_COLOR)), null, Font.BOLD)); - IToken keywordsValuesToken = new Token(new TextAttribute(provider.getColor(PreferenceConverter.getColor(store, PreferenceConstants.P_KVAL_COLOR)))); - IToken referenceToken = new Token(new TextAttribute(provider.getColor(PreferenceConverter.getColor(store, PreferenceConstants.P_REF_COLOR)), null, Font.BOLD)); - IToken definitionsToken = new Token(new TextAttribute(provider.getColor(PreferenceConverter.getColor(store, PreferenceConstants.P_DEF_COLOR)), null, Font.ITALIC)); - - List rules = Lists.newArrayList(); - // trap instruction within quotes first to prevent being picked up by next rules - rules.add(new EndOfLineRule("\"#%", instructToken)); - - // rule for Strings - may span multiple lines - rules.add(new MultiLineRule("\"", "\"", stringToken)); - rules.add(new MultiLineRule("\'", "\'", stringToken)); - - rules.add(new EndOfLineRule("#%", instructToken)); - // rule for comments - ended by a line delimiter - rules.add(new EndOfLineRule("#", commentToken)); - - WordRule wordRule = RuleFactory.buildRule(ImpexRules.KEYWORD, null); - // rule for modifiers - for (String word : Formatter.IMPEX_KEYWORDS_ATTRIBUTES) { - wordRule.addWord(word, modifiersToken); - } - - // rule for impex tags - for (String header : Formatter.HEADER_MODE_PROPOSALS) { - wordRule.addWord(header, impexTagsToken); - } - - // rule for keyword values - for (String value : Formatter.KEYWORDS_VALUES) { - wordRule.addWord(value, keywordsValuesToken); - } - - rules.add(wordRule); - - // rule for definitions - wordRule = RuleFactory.buildRule(ImpexRules.VARIABLE, definitionsToken); - rules.add(wordRule); - wordRule = RuleFactory.buildRule(ImpexRules.REFERENCE, referenceToken); - rules.add(wordRule); - - wordRule = RuleFactory.buildRule(ImpexRules.SEMICOLON, modifiersToken); - rules.add(wordRule); - wordRule = RuleFactory.buildRule(ImpexRules.COMMA, modifiersToken); - rules.add(wordRule); - - IRule[] ruleArray = new IRule[rules.size()]; - setRules(rules.toArray(ruleArray)); - } -} diff --git a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/scanners/InstructionsRuleScanner.java b/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/scanners/InstructionsRuleScanner.java deleted file mode 100755 index 4990884f..00000000 --- a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/scanners/InstructionsRuleScanner.java +++ /dev/null @@ -1,75 +0,0 @@ -/******************************************************************************* - * Copyright 2020 SAP - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy - * of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - ******************************************************************************/ -package com.hybris.impexformatter.scanners; - -import java.awt.Font; -import java.util.List; - -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.preference.PreferenceConverter; -import org.eclipse.jface.text.TextAttribute; -import org.eclipse.jface.text.rules.EndOfLineRule; -import org.eclipse.jface.text.rules.IRule; -import org.eclipse.jface.text.rules.IToken; -import org.eclipse.jface.text.rules.MultiLineRule; -import org.eclipse.jface.text.rules.RuleBasedScanner; -import org.eclipse.jface.text.rules.Token; -import org.eclipse.jface.text.rules.WordRule; - -import com.google.common.collect.Lists; -import com.hybris.impexformatter.Activator; -import com.hybris.impexformatter.actions.Formatter; -import com.hybris.impexformatter.editors.ColorProvider; -import com.hybris.impexformatter.preferences.PreferenceConstants; -import com.hybris.impexformatter.rules.RuleFactory; -import com.hybris.impexformatter.rules.RuleFactory.ImpexRules; - -/** - * Scanner which contains sequence of rules - */ -public class InstructionsRuleScanner extends RuleBasedScanner { - - IPreferenceStore store = Activator.getDefault().getPreferenceStore(); - - public InstructionsRuleScanner(ColorProvider provider) { - IToken stringToken = new Token(new TextAttribute(provider.getColor(PreferenceConverter.getColor(store, PreferenceConstants.P_STRING_COLOR)))); - IToken commentToken = new Token(new TextAttribute(provider.getColor(PreferenceConverter.getColor(store, PreferenceConstants.P_COMMENT_COLOR)))); - IToken instructToken = new Token(new TextAttribute(provider.getColor(PreferenceConverter.getColor(store, PreferenceConstants.P_INSTRUCT_COLOR)), null, Font.ITALIC)); - IToken definitionsToken = new Token(new TextAttribute(provider.getColor(PreferenceConverter.getColor(store, PreferenceConstants.P_DEF_COLOR)), null, Font.ITALIC)); - - List rules = Lists.newArrayList(); - // rule for Strings - may spanning multiple lines - rules.add(new MultiLineRule("\"", "\"", stringToken)); - rules.add(new MultiLineRule("\'", "\'", stringToken)); - rules.add(new EndOfLineRule("#%", instructToken)); - // rule for comments - ended by a line delimiter - rules.add(new EndOfLineRule("//", commentToken)); - - WordRule wordRule = RuleFactory.buildRule(ImpexRules.KEYWORD, null); - // rule for instructions - for (String word : Formatter.INSTRUCTION_CLASS_PROPOSALS) { - wordRule.addWord(word, instructToken); - } - - rules.add(wordRule); - - // rule for definitions - wordRule = RuleFactory.buildRule(ImpexRules.VARIABLE, definitionsToken); - rules.add(wordRule); - IRule[] ruleArray = new IRule[rules.size()]; - setRules(rules.toArray(ruleArray)); - } -} diff --git a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/utils/ColorHelper.java b/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/utils/ColorHelper.java deleted file mode 100755 index f8ba1923..00000000 --- a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/utils/ColorHelper.java +++ /dev/null @@ -1,32 +0,0 @@ -/******************************************************************************* - * Copyright 2020 SAP - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy - * of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - ******************************************************************************/ -package com.hybris.impexformatter.utils; - -import org.eclipse.swt.graphics.RGB; - -public class ColorHelper { - - public static final String rgbTohex(RGB color) { - Integer value = color.blue | (color.green << 8) | (color.red << 16); - return '#' + Integer.toHexString(value); - } - - public static final RGB hexTorgb(String color) { - java.awt.Color result = java.awt.Color.decode(color); - RGB rgb = new RGB(result.getRed(), result.getGreen(), result.getBlue()); - return rgb; - } -} diff --git a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/utils/StringHelper.java b/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/utils/StringHelper.java deleted file mode 100644 index a5e13f64..00000000 --- a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/utils/StringHelper.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.hybris.impexformatter.utils; - -public class StringHelper { - - /** - * checks if in

typecode
is possible to find
prefix
. Case insensitive. - * @param typeCode that is main string - * @param prefix check if given prefix exists - * @return true if there is a match case insensitive and is less than main string. - */ - public static boolean findMatches(String typeCode, String prefix) { - String tcUp = typeCode.toUpperCase(); - String cpUp = prefix.toUpperCase(); - return tcUp.startsWith(cpUp) && prefix.length() < typeCode.length(); - } - - -} diff --git a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/wizards/NewImpexWizard.java b/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/wizards/NewImpexWizard.java deleted file mode 100755 index 85745ef4..00000000 --- a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/wizards/NewImpexWizard.java +++ /dev/null @@ -1,166 +0,0 @@ -/******************************************************************************* - * Copyright 2020 SAP - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy - * of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - ******************************************************************************/ -package com.hybris.impexformatter.wizards; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.lang.reflect.InvocationTargetException; -import java.util.HashMap; - -import org.eclipse.core.resources.IContainer; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IMarker; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.resources.IWorkspaceRoot; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Path; -import org.eclipse.core.runtime.Status; -import org.eclipse.jface.dialogs.MessageDialog; -import org.eclipse.jface.operation.IRunnableWithProgress; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.jface.wizard.Wizard; -import org.eclipse.ui.INewWizard; -import org.eclipse.ui.IWorkbench; -import org.eclipse.ui.IWorkbenchPage; -import org.eclipse.ui.PartInitException; -import org.eclipse.ui.PlatformUI; -import org.eclipse.ui.ide.IDE; - -import com.hybris.impexformatter.Activator; - -public class NewImpexWizard extends Wizard implements INewWizard { - - private NewImpexWizardPage wizardPage; - private ISelection currentSelection; - - public NewImpexWizard() { - super(); - setNeedsProgressMonitor(true); - } - - @Override - public void addPages() { - wizardPage = new NewImpexWizardPage(currentSelection); - addPage(wizardPage); - } - - public void setCurrentSelection(ISelection selection) { - this.currentSelection = selection; - } - - @Override - public boolean performFinish() { - final String containerName = wizardPage.getContainerName(); - final String fileName = wizardPage.getFileName(); - IRunnableWithProgress irwp = new IRunnableWithProgress() { - public void run(IProgressMonitor ipm) throws InvocationTargetException { - try { - createSampleFile(ipm, containerName, fileName); - } - catch (CoreException ce) { - throw new InvocationTargetException(ce); - } - finally { - ipm.done(); - } - } - }; - try { - getContainer().run(true, false, irwp); - } - catch (InterruptedException ie) { - Thread.currentThread().interrupt(); - return false; - } - catch (InvocationTargetException ite) { - Throwable realException = ite.getTargetException(); - MessageDialog.openError(getShell(), "Error", realException.getMessage()); - return false; - } - return true; - } - - private void createSampleFile(IProgressMonitor monitor, String containerName, String fileName) throws CoreException { - - monitor.beginTask("Creating " + fileName, 2); - IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); - IResource resource = root.findMember(new Path(containerName)); - if (!resource.exists() || !(resource instanceof IContainer)) { - throwCoreException("Container \"" + containerName + "\" does not exist."); - } - IContainer container = (IContainer) resource; - final IFile file = container.getFile(new Path(fileName)); - try { - InputStream stream = openContentStream(); - if (file.exists()) { - file.setContents(stream, true, true, monitor); - } - else { - file.create(stream, true, monitor); - } - if (stream != null) { - stream.close(); - } - } - catch (IOException e) { - Activator.logError("IOException", e); - } - monitor.worked(1); - monitor.setTaskName("Opening file for editing..."); - - getShell().getDisplay().asyncExec(new Runnable() { - public void run() { - IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); - try { - HashMap map = new HashMap(); - map.put(IDE.EDITOR_ID_ATTR, "com.hybris.impexformatter.editors.ImpexPageEditor"); - IMarker marker = file.createMarker(IMarker.TEXT); - marker.setAttributes(map); - IDE.openEditor(page, marker, true); - marker.delete(); - } - catch (PartInitException e) { - Activator.logError("PartInitException", e); - } - catch (CoreException e) { - Activator.logError("CoreException", e); - } - } - }); - monitor.worked(1); - } - - private InputStream openContentStream() { - String contents = "# USE CTRL-SPACE for type-ahead support\n"; - return new ByteArrayInputStream(contents.getBytes()); - } - - private void throwCoreException(String message) throws CoreException { - IStatus status = new Status(IStatus.ERROR, "impexFormatter", IStatus.OK, message, null); - throw new CoreException(status); - } - - @Override - public void init(IWorkbench workbench, IStructuredSelection selection) { - this.currentSelection = selection; - } - -} diff --git a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/wizards/NewImpexWizardPage.java b/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/wizards/NewImpexWizardPage.java deleted file mode 100755 index 11e4af58..00000000 --- a/com.hybris.hyeclipse.impexed/src/com/hybris/impexformatter/wizards/NewImpexWizardPage.java +++ /dev/null @@ -1,191 +0,0 @@ -/******************************************************************************* - * Copyright 2020 SAP - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy - * of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - ******************************************************************************/ -package com.hybris.impexformatter.wizards; - -import org.eclipse.core.resources.IContainer; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.IAdaptable; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.Path; -import org.eclipse.jdt.core.IPackageFragment; -import org.eclipse.jdt.core.IPackageFragmentRoot; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.jface.viewers.TreePath; -import org.eclipse.jface.viewers.TreeSelection; -import org.eclipse.jface.wizard.WizardPage; -import org.eclipse.swt.SWT; -import org.eclipse.swt.events.ModifyEvent; -import org.eclipse.swt.events.ModifyListener; -import org.eclipse.swt.events.SelectionAdapter; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.Button; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Label; -import org.eclipse.swt.widgets.Text; -import org.eclipse.ui.dialogs.ContainerSelectionDialog; - -public class NewImpexWizardPage extends WizardPage { - - private Text containerText; - private Text fileText; - private ISelection selection; - - public NewImpexWizardPage(ISelection selection) { - super("wizardPage"); - setTitle("New Impex File"); - setDescription("This wizard creates a new file with a *.impex extension that can be used with the Impex editor."); - this.selection = selection; - } - - @Override - public void createControl(Composite parent) { - Composite container = new Composite(parent, SWT.NULL); - GridLayout layout = new GridLayout(); - container.setLayout(layout); - layout.numColumns = 3; - layout.verticalSpacing = 9; - Label label = new Label(container, SWT.NULL); - label.setText("&Project/Folder:"); - - containerText = new Text(container, SWT.BORDER | SWT.SINGLE); - GridData gd = new GridData(GridData.FILL_HORIZONTAL); - containerText.setLayoutData(gd); - containerText.addModifyListener(new ModifyListener() { - public void modifyText(ModifyEvent e) { - dialogChanged(); - } - }); - - Button button = new Button(container, SWT.PUSH); - button.setText("Browse..."); - button.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent e) { - handleBrowse(); - } - }); - label = new Label(container, SWT.NULL); - label.setText("&File name:"); - - fileText = new Text(container, SWT.BORDER | SWT.SINGLE); - gd = new GridData(GridData.FILL_HORIZONTAL); - fileText.setLayoutData(gd); - fileText.addModifyListener(new ModifyListener() { - public void modifyText(ModifyEvent e) { - dialogChanged(); - } - }); - initialize(); - dialogChanged(); - setControl(container); - } - - private void initialize() { - if (selection != null && selection.isEmpty() == false && selection instanceof IStructuredSelection ssel) { - if (ssel.size() > 1) - return; - Object obj = ssel.getFirstElement(); - if (obj instanceof IResource) { - IContainer container; - if (obj instanceof IContainer iContainer) - container = iContainer; - else - container = ((IResource) obj).getParent(); - containerText.setText(container.getFullPath().toString()); - } - else if (ssel instanceof TreeSelection treeSelection) { - TreePath[] treePaths = treeSelection.getPaths(); - TreePath treePath = treePaths[0]; - Object lastSegmentObj = treePath.getLastSegment(); - if (lastSegmentObj instanceof IPackageFragmentRoot) { - IPackageFragmentRoot packageRoot = (IPackageFragmentRoot) ((IAdaptable) lastSegmentObj).getAdapter(IPackageFragmentRoot.class); - IPath packagePath = packageRoot.getPath(); - containerText.setText(packagePath.toString()); - } - else if (lastSegmentObj instanceof IPackageFragment) { - IPackageFragment packageFragment = (IPackageFragment) ((IAdaptable) lastSegmentObj).getAdapter(IPackageFragment.class); - if (packageFragment != null) { - IPath packagePath = packageFragment.getPath(); - containerText.setText(packagePath.toString()); - } - } - } - } - fileText.setText("test.impex"); - } - - private void handleBrowse() { - ContainerSelectionDialog dialog = new ContainerSelectionDialog(getShell(), ResourcesPlugin.getWorkspace() - .getRoot(), false, "Select Project/Folder"); - if (dialog.open() == ContainerSelectionDialog.OK) { - Object[] result = dialog.getResult(); - if (result.length == 1) { - containerText.setText(((Path) result[0]).toString()); - } - } - } - - private void dialogChanged() { - IResource container = ResourcesPlugin.getWorkspace().getRoot().findMember(new Path(getContainerName())); - String fileName = getFileName(); - - if (getContainerName().length() == 0) { - updateStatus("Project/Folder must be specified"); - return; - } - if (container == null || (container.getType() & (IResource.PROJECT | IResource.FOLDER)) == 0) { - updateStatus("Project/Folder must exist"); - return; - } - if (!container.isAccessible()) { - updateStatus("Project/Folder must be writable"); - return; - } - if (fileName.length() == 0) { - updateStatus("File name must be specified"); - return; - } - if (fileName.replace('\\', '/').indexOf('/', 1) > 0) { - updateStatus("File name must be valid"); - return; - } - int dotLoc = fileName.lastIndexOf('.'); - if (dotLoc != -1) { - String ext = fileName.substring(dotLoc + 1); - if (ext.equalsIgnoreCase("impex") == false && ext.equalsIgnoreCase("csv") == false) { - updateStatus("File extension must be \"impex\" or \"csv\""); - return; - } - } - updateStatus(null); - } - - private void updateStatus(String message) { - setErrorMessage(message); - setPageComplete(message == null); - } - - public String getContainerName() { - return containerText.getText(); - } - - public String getFileName() { - return fileText.getText(); - } -} diff --git a/com.hybris.hyeclipse.impexed/test.impex b/com.hybris.hyeclipse.impexed/test.impex deleted file mode 100755 index 8853933e..00000000 --- a/com.hybris.hyeclipse.impexed/test.impex +++ /dev/null @@ -1,207 +0,0 @@ -# Einheiten -# Hier werden alle Einheiten wie g, Kg, ml, usw. eingetragen. Dabei mĂĽssen alle Einheiten die aus der -# "20130524_ Checkliste Compexpflege mit Datentyp IDs.xlsx" (aus allen Wertelisten) entnommen werden hintereinander weg aufgezählt werden. -# Jede Einheit muss dazu mit einer eineindeutigen ID versehen werden. In unserem Beispiel ist das 1,2,3,4,5,6. Zusätzlich kann ein Einheitentyp -# angegeben werden hier gewicht, länge... der fĂĽr spätere konvertierungen genutzt werden kann. Das Typ-Feld ist dabei kann pflichtfeld. -# Der englische und der deutsche name wurden hier auf den Wert des Symbols gesetzt. Auf der grafischen Oberfläche wird später nur das Symbol angezeigt. -# INSERT_UPDATE ClassificationAttributeUnit -> Ein Befehl zum erstellen/aktuallisieren von Merkmalseinheiten. Unterhalb des Headers bleiben die Zeilen leer. -# code[unique=true] -> Eine eineindeutige ID fĂĽr die Einheit. Unterhalb des Headers werden alle Einheiten ID's eingetragen. -# name[lang=de] -> Der deutsche Name der Einheit. Unterhalb des Headers werden alle deutschen Namen der Einheit eingetragen. -# name[lang=en] -> Der englische Name der Einheit. Unterhalb des Headers werden alle englischen Namen der Einheit eingetragen. -# unitType -> Der Typ der Einheit. Unterhalb des Headers werden die Typen eingetragen, falls notwendig. -# $classSystemVersion -> Die Version der Klassifizierung. Unterhalb des Headers bleiben die Zeilen leer. -> von SL mit default gesetzt - -# Pflichtfelder: code[unique=true] name[lang=de] name[lang=en] symbol - -INSERT_UPDATE Order; code[unique=true]; \ - @template1[translator=de.hybris.jakarta.ext.impex.jalo.translators.VelocityTranslator, expr='$item.user.getUID()']; \ - @template2[translator=de.hybris.jakarta.ext.impex.jalo.translators.VelocityTranslator, expr='$item.user.name']; \ - "@template3[translator=de.hybris.jakarta.ext.impex.jalo.translators.VelocityTranslator, expr='$item.paymentAddress.getAttribute(""streetname"")']"; \ - @template4[translator=de.hybris.jakarta.ext.impex.jalo.translators.VelocityTranslator, expr='$item.paymentAddress.country.IsoCode'] - -INSERT_UPDATE ClassificationAttributeUnit;code[unique=true];name[lang=de];name[lang=en];symbol;unitType;$classSystemVersion -;1;ml;ml;ml;Fuellmenge -;2;g;g;g;Gewicht -;3;kg;kg;kg;Gewicht -;4;L;L;L;Fuellmenge -;5;WL;WL;WL;Fuellmenge -;6;m;m;m;Laenge - - - -# Wertelisten -# Hier werden alle Wertelisten, die später aus einem DropDown-MenĂĽ gewählt werden können, eingetragen. Die Beispieldaten wurden aus der -# "20130524_ Checkliste Compexpflege mit Datentyp IDs.xlsx" entnommen. Es ist zu beachten, dass nur nichtkomplexe Wertelisten eingetragen werden. -# Nicht komplexe Wertelisten sind Wertelisten, die nur eine ID und einen Bezeichner enthalten. Komplexere Wertelisten werden später als Objekte in der Hybris -# abgebildet und an das Produkt gehängt. (Beispiel komplexe Werteliste: Operative Einheit). Alle Werte aus den nicht komplexen Wertelisten werden hier aufgelistet. -# Jeder Wert muss dazu mit einer eineindeutigen ID versehen werden (code[unique=true]). In unserem Beispiel ist das WL1,WL2,WL3,... . Das Feld "externalid" enthält -# die CompexID's wie diese in der Datei "20130524_ Checkliste Compexpflege mit Datentyp IDs.xlsx" mitgeliefert wurden. -# Bei nicht vorhandener ID wurde der Bezeichner als ID eingetragen. -# INSERT_UPDATE ClassificationAttributeValue -> Ein Befehl zum erstellen/aktuallisieren von Wertelisten. Unterhalb des Headers bleiben die Zeilen leer. -# code[unique=true] -> Eine eineindeutige ID fĂĽr den Wert. Unterhalb des Headers werden alle Werte ID's eingetragen. -# externalid -> Eine nicht eineindeutige Compex ID. Unterhalb des Headers werden alle Compex ID's eingetragen. -# name[lang=de] -> Der deutsche Name des Wertes. Unterhalb des Headers werden alle deutschen Namen der Werte eingetragen. -# name[lang=en] -> Der englische Name des Wertes. Unterhalb des Headers werden alle englischen Namen der Werte eingetragen. -# $classSystemVersion -> Die Version der Klassifizierung. Unterhalb des Headers bleiben die Zeilen leer. -> von SL mit default gesetzt - -# Pflichtfelder: code[unique=true] externalid name[lang=de] name[lang=en] - -INSERT_UPDATE ClassificationAttributeValue;code[unique=true];externalid;name[lang=de];name[lang=en];$classSystemVersion -;WL1;1;Basis 1 KG;Basis 1 KG -;WL2;100;Basis 100 gr;Basis 100 gr -;WL3;0;keine Zuordnung;keine Zuordnung -;WL4;2;GemĂĽse;GemĂĽse -;WL5;3;TrockenfrĂĽchte/NĂĽsse;TrockenfrĂĽchte/NĂĽsse -;WL6;4;Frische Kräuter;Frische Kräuter -;WL7;5;vom Schwein;vom Schwein -;WL8;6;vom Rind;vom Rind -;WL9;7;vom Kalb;vom Kalb -;WL10;8;vom Lamm;vom Lamm -;WL11;9;GeflĂĽgel;GeflĂĽgel -;WL12;10;Hackfleisch;Hackfleisch -;WL13;11;Sonstiges Fleisch;Sonstiges Fleisch -;WL14;12;WĂĽrstchen;WĂĽrstchen -;WL15;13;Speck & Schinken;Speck & Schinken -;WL16;14;Salami & Dauerwurst;Salami & Dauerwurst -;WL17;15;Streichwurst;Streichwurst -;WL18;16;Aufschnitt;Aufschnitt - -# Klassifizierende Merkmale -# Hier werden alle Merkmale aufgelistet, die in den Klassifikationen auftauchen können (ohne die Klassifikation: AllgemeingĂĽltige Attribute). -# Diese Merkmale wurden aus der XML-Datei (Klassifizierung Stand 08.07.2013.xlsx) extrahiert. -# Die ID's wie "ARKU_400_0018" wurden von Softlution als Provisorium erstellt um ID's wie "Erfasser des Artikels" zu vermeiden. -# INSERT_UPDATE ClassificationAttribute -> Ein Befehl zum erstellen/aktualisieren von Klassifikationensattributen. Unterhalb des Headers bleiben die Zeilen leer. -# code[unique=true] -> Eine eineindeutige ID fĂĽr die Klassifikation. Unterhalb des Headers werden alle Klassifikations ID's eingetragen. -# name[lang=de] -> Der deutsche Name der Klassifikation. Unterhalb des Headers werden alle deutschen Namen der Klassifikationen eingetragen. -# name[lang=en] -> Der englische Name der Klassifikation. Unterhalb des Headers werden alle englischen Namen der Klassifikationen eingetragen. -# Als Namen wurden die Hybris Bezeichner aus der XML-Datei (20130524_ Checkliste Compexpflege mit Datentyp IDs.xlsx) genommen. -# $classSystemVersion -> Die Version der Klassifizierung. Unterhalb des Headers bleiben die Zeilen leer. -> von SL mit default gesetzt - -# Pflichtfelder: code[unique=true] name[lang=de] name[lang=en] - -INSERT_UPDATE ClassificationAttribute;code[unique=true];name[lang=de];name[lang=en];$classSystemVersion -;ARKU_400_0018;Waagen Zuordnung;Waagen Zuordnung -;ARKU_423_0001;Grundpreis Basis;Grundpreis Basis -;ARKU_423_0002;gĂĽltig ab;gĂĽltig ab -;ARKU_423_0003;gĂĽltig bis;gĂĽltig bis -;ARKU_423_0004;Grundpreis Inhalt;Grundpreis Inhalt -;ARKU_423_0005;Nettoinhalt/Abtropfgewicht;Nettoinhalt/Abtropfgewicht -;ARKU_400_0026;Nachkommastellen;Nachkommastellen -;ARKU_400_0031;Pfand;Pfand -;ARKU_400_0032;Leergut;Leergut -;ARKU_400_0033;Gefahrgut;Gefahrgut -;ARKU_432_0004;Durchschnittsgewicht;Durchschnittsgewicht -;ARKU_432_0005;Erfasser des Artikels;Erfasser des Artikels - -# Klassifikationen -# Hier werden zunächst alle Klassifizierungen angelegt. -# INSERT_UPDATE ClassificationClass -> Ein Befehl zum erstellen/aktuallisieren von Klassifikationen. Unterhalb des Headers bleiben die Zeilen leer. -# code[unique=true] -> Eine eineindeutige ID fĂĽr die Klassifikation. Unterhalb des Headers werden alle Klassifikations ID's eingetragen. -# name[lang=de] -> Der deutsche Name der Klassifikation. Unterhalb des Headers werden alle deutschen Namen der Klassifikationen eingetragen. -# name[lang=en] -> Der englische Name der Klassifikation. Unterhalb des Headers werden alle englischen Namen der Klassifikationen eingetragen. -# Als Namen wurden die Bezeichner aus der XML-Datei (Klassifizierung Stand 08.07.2013.xlsx) genommen. -# allowedPrincipals(uid)[default='customergroup'] -> Die Nutzergruppe, die auf die Klassifikation zugreifen dĂĽrfen. Unterhalb des Headers können berechtigte Gruppen eingetragen werden. -> von SL mit default gesetzt -# $classCatalogVersion -> Die Version der Klassifizierung. Unterhalb des Headers bleiben die Zeilen leer. -> von SL mit default gesetzt - -# Pflichtfelder: code[unique=true] name[lang=de] name[lang=en] - -INSERT_UPDATE ClassificationClass;code[unique=true];name[lang=de];name[lang=en];$classCatalogVersion;allowedPrincipals(uid)[default='customergroup'] -;Zuordnungspflichtig;Zuordnungspflichtig;Zuordnungspflichtig -;Sortimentsartikel;Sortimentsartikel;Sortimentsartikel -;Lebensmittel und lebenmittelnahe Produkte;Lebensmittel und lebenmittelnahe Produkte;Lebensmittel und lebenmittelnahe Produkte -;nicht Lebensmittel (NF II);nicht Lebensmittel (NF II);nicht Lebensmittel (NF II) -;Obst/GemĂĽse/Blumen;Obst/GemĂĽse/Blumen;Obst/GemĂĽse/Blumen -;Obst/GemĂĽse;Obst/GemĂĽse;Obst/GemĂĽse -;Fresh Cut;Fresh Cut;Fresh Cut -;Blumen;Blumen;Blumen -;Bedienung;Bedienung;Bedienung -;interne Artikel;interne Artikel;interne Artikel -;systemtechnische Artikel;systemtechnische Artikel;systemtechnische Artikel -;Ladehilfsmittel und Transporthilfsmittel;Ladehilfsmittel und Transporthilfsmittel;Ladehilfsmittel und Transporthilfsmittel -;Verbrauchsmaterial;Verbrauchsmaterial;Verbrauchsmaterial -;technische Artikel;technische Artikel;technische Artikel -;nicht logistische Artikel;nicht logistische Artikel;nicht logistische Artikel -;Gruppenartikel Wert;Gruppenartikel Wert;Gruppenartikel Wert -;Gruppenartikel Menge/ Wert;Gruppenartikel Menge/ Wert;Gruppenartikel Menge/ Wert -;Pfand/Leergut Artikel;Pfand/Leergut Artikel;Pfand/Leergut Artikel -;Zusatz;Zusatz;Zusatz -;Eigenmarken;Eigenmarken;Eigenmarken -;Gefahrgut;Gefahrgut;Gefahrgut -;KĂĽhlpflichtig;KĂĽhlpflichtig;KĂĽhlpflichtig -;Online Artikel;Online Artikel;Online Artikel -;Pfandbehaftet;Pfandbehaftet;Pfandbehaftet - -# Klassifikationsbaum -# Hier wird der Klassifikationsbaum aus der Excel-Datei (Klassifizierung Stand 08.07.2013.xlsx) aufgebaut. Dazu wurden die Spalten B bis E genutzt. -# Die Spalte A wurde ignoriert, da die dort aufgelisteten Attribute schon am Produkt existieren sollen. -# INSERT_UPDATE CategoryCategoryRelation -> Ein Befehl zum erstellen/aktuallisieren von Klassifikationensabhängigkeiten. Unterhalb des Headers bleiben die Zeilen leer. -# $categories -> Die ID einer Subklassifikation -# $supercategories -> Die ID einer Oberkategorie -# Beispiel ($categories <-> $supercategories): Blumen <-> Obst/GemĂĽse/Blumen - -# Pflichtfelder: $categories $supercategories - -INSERT_UPDATE CategoryCategoryRelation;$categories;$supercategories -;Sortimentsartikel;Zuordnungspflichtig -;interne Artikel;Zuordnungspflichtig -;technische Artikel;Zuordnungspflichtig - -;Lebensmittel und lebenmittelnahe Produkte;Sortimentsartikel -;nicht Lebensmittel (NF II);Sortimentsartikel -;Obst/GemĂĽse/Blumen;Sortimentsartikel -;Bedienung;Sortimentsartikel - -;Obst/GemĂĽse;Obst/GemĂĽse/Blumen -;Fresh Cut;Obst/GemĂĽse/Blumen -;Blumen;Obst/GemĂĽse/Blumen - -;systemtechnische Artikel;interne Artikel -;Ladehilfsmittel und Transporthilfsmittel;interne Artikel -;Verbrauchsmaterial;interne Artikel - -;nicht logistische Artikel;technische Artikel -;Gruppenartikel Wert;nicht logistische Artikel -;Gruppenartikel Menge/ Wert;nicht logistische Artikel -;Pfand/Leergut Artikel;technische Artikel - -;Eigenmarken;Zusatz -;Gefahrgut;Zusatz -;KĂĽhlpflichtig;Zusatz -;Online Artikel;Zusatz -;Pfandbehaftet;Zusatz - -# Wertelisten -# Hier werden alle Wertelisten, die später aus einem DropDown-MenĂĽ gewählt werden können, eingetragen. Die Beispieldaten wurden aus der -# "20130524_ Checkliste Compexpflege mit Datentyp IDs.xlsx" entnommen. Es ist zu beachten, dass nur nichtkomplexe Wertelisten eingetragen werden. -# Nicht komplexe Wertelisten sind Wertelisten, die nur eine ID und einen Bezeichner enthalten. Komplexere Wertelisten werden später als Objekte in der Hybris -# abgebildet und an das Produkt gehängt. (Beispiel komplexe Werteliste: Operative Einheit). Alle Werte aus den nicht komplexen Wertelisten werden hier aufgelistet. -# Jeder Wert muss dazu mit einer eineindeutigen ID versehen werden (code[unique=true]). In unserem Beispiel ist das WL1,WL2,WL3,... . Das Feld "externalid" enthält -# die CompexID's wie diese in der Datei "20130524_ Checkliste Compexpflege mit Datentyp IDs.xlsx" mitgeliefert wurden. -# Bei nicht vorhandener ID wurde der Bezeichner als ID eingetragen. -# INSERT_UPDATE ClassAttributeAssignment -> Ein Befehl zum erstellen/aktuallisieren von Zuweisungen zwischen Merkmal und Klassifikation. Unterhalb des Headers bleiben die Zeilen leer. -# $class -> Die Klasse der ein Merkmal zugewiesen werden soll. -# $attribute - Das Merkmal, dass einer Klassifizierung zugewiesen werden soll. -# attributeType(code) -> Der Typ eines Merkmals. Hierbei ist zu beachten, dass Hybris nur die Typen date, number, string, boolean und enum kennt. -# Enums sind die oben angelegten Wertelisten, die als DropDown-MenĂĽ angezeigt werden sollen. FĂĽr jeden wert, muss dabei eine neue Zeile angelegt werden. -# $attributeValues -> Der Wert aus einer Werteliste, der einem Merkmal zugeordnet werden soll. Dieses Feld wird nur ausgefĂĽllt, wenn der Merkmalstyp 'enum' gewählt wurde. Bleibt sonst leer -# $unit -> Die ID einer Einheit, die neben dem Merkmal angeziegt/gewählt werden kann. -# multivalued[default=false] -> Dieses Feld kann auf 'true' gesetzt werden, falls mehrere Werte aus einer DropDown-Liste gewählt werden sollen. - -# Pflichtfelder: $class $attribute attributeType(code) $attributeValues {nur bei enum} multivalued[default=false] {nur wenn mehrere Werte gewählt werden sollen} - -INSERT_UPDATE ClassAttributeAssignment;$class;$attribute;attributeType(code);$attributeValues;$unit;multivalued[default=false];$classSystemVersion -;Sortimentsartikel;ARKU_423_0001;enum;WL1; -;Sortimentsartikel;ARKU_423_0001;enum;WL2; -;Sortimentsartikel;ARKU_423_0002;date;; -;Sortimentsartikel;ARKU_423_0003;date;; -;Sortimentsartikel;ARKU_423_0004;number;;1 -;Sortimentsartikel;ARKU_423_0005;number;;1 -;Sortimentsartikel;ARKU_415_0007;boolean;; -;Sortimentsartikel;ARKU_415_0008;boolean;; -;Sortimentsartikel;ARKU_415_0025;number;; -;Sortimentsartikel;ARKU_415_0026;number;; -;Sortimentsartikel;LILA_501_0001;string;; -;Sortimentsartikel;LILA_501_0002;date;; -;Sortimentsartikel;LILA_501_0003;string;; -;Sortimentsartikel;LILA_501_0004;date;; - diff --git a/docs/dev/impex/editor-replacement-plan.md b/docs/dev/impex/editor-replacement-plan.md index 9c418f44..531ead66 100644 --- a/docs/dev/impex/editor-replacement-plan.md +++ b/docs/dev/impex/editor-replacement-plan.md @@ -1,6 +1,26 @@ # ImpEx editor replacement plan -Status: migration started on `feature/impex-lsp-migration`; legacy editor retained. +Status: cutover approved on 23 November 2026; legacy source/bundle removed on `feature/impex-lsp-migration`. + +## Approved cutover + +The user approved removal of the old editor. `com.hybris.hyeclipse.impexed` is +removed from the source, reactor, feature, and test dependencies. The replacement +is now named **ImpEx Editor** and registered as the default for `.impex` files. +Existing wizard/command IDs are preserved for user key bindings, not as dependencies +on the removed implementation. The phases and verification history below record +the original coexistence rollout. + +Manual UI/upgrade checks and known grammar/compatibility refinements remain pending; +cutover approval is not a claim that those checks passed. Existing installations may +need editor reassociation and explicit removal of an independently installed old bundle. +Published release/update-site history is unchanged. See the replacement bundle's +README for upgrade notes. + +Cutover verification: all 171 tests passed both in a clean build with local artifacts +ignored and in the normal cached build. Runtime registration tests confirm the old +bundle/editor/formatter contributions are absent and the replacement is default. +The new p2 ZIP, feature, and metadata exclude the retired bundle. ## Implementation progress @@ -60,17 +80,17 @@ Status: migration started on `feature/impex-lsp-migration`; legacy editor retain - Verification: all 171 tests passed in the full reactor, including 80 ImpEx tests. Tests cover hover/outline ranges, quote origins, surrogate pairs, notification lifecycle, rapid edits/reopening, and real JSON-RPC hover/symbol/diagnostic exchange. -- Next: interactive UI/upgrade checks and CSV/header compatibility refinements. TextMate continuation - highlighting still needs refinement. The legacy editor must not be retired yet. +- Next: interactive UI/upgrade checks and CSV/header compatibility refinements. + TextMate continuation highlighting still needs refinement; the approved cutover + proceeds with these limitations documented rather than retaining the old source. ## Goal and scope Replace the custom `com.hybris.hyeclipse.impexed` editor with Eclipse's Generic Editor, TM4E syntax highlighting, and LSP4E-backed language services. Formatting, type-system completion, and the new-file wizard are mandatory replacement -features. Highlighting-only builds are opt-in previews, not the completed -replacement; retire the legacy editor only after these features pass acceptance -tests and the remaining migration decisions are resolved. +features. The original plan used opt-in previews before cutover; the user has now +approved retirement while the remaining manual checks and compatibility work are tracked. Inputs: @@ -79,8 +99,8 @@ Inputs: verification against the supported Commerce version. - [TextMate grammar](../../../com.hybris.hyeclipse.impex/syntaxes/impex.tmLanguage.json): canonical packaged grammar, still under migration. -- Existing `com.hybris.hyeclipse.impexed/plugin.xml`, editor, wizard, formatter, - completion processors, and hyperlink classes. +- Legacy editor, wizard, formatter, completion processors, and hyperlink classes, + available in Git history before the cutover commit. ## Architecture @@ -120,8 +140,8 @@ p2 feature resolves these dependencies, not just the development target. The original supplied grammar started a string on any quote, treated `\\.` as an escape, recognized only unquoted `#` comments, and could not distinguish -scripts from comments. The preview fixes initial cases; complete and validate -the following behavior before editor cutover: +scripts from comments. The replacement fixes initial cases; the remaining grammar +review findings and the following behavior require follow-up after the approved cutover: - Model cell boundaries and quoted multiline cells; quoting starts at the beginning of a cell, allowing leading whitespace as verified by fixtures. @@ -206,11 +226,11 @@ before changing the default editor: | Custom auto-edit/comment behavior | TM4E language configuration where safe; verify against data cells | | Old editor IDs/preferences | Document reassociation and preference changes; migrate only with explicit policy | -Remove the old editor from the main feature/reactor only after parity decisions -and upgrade tests pass. Test upgrades from an existing installation: dropping a -bundle from a feature does not by itself prove old associations or installed -bundles disappear. Keep a temporary opt-in legacy feature if gaps require it. -Do not delete the old source or published update-site history during the spike. +The approved cutover removes the old source and bundle from the main feature/reactor. +Still test upgrades from existing installations: dropping a bundle from a feature +does not prove old associations or independently installed bundles disappear. +Preserve user workspace preferences and published update-site history; document +manual reassociation/uninstallation rather than silently changing them. ## Required feature specifications @@ -307,8 +327,8 @@ editor opening, shortcut/command routing, and operation without language service Unicode, external files, themes, and old workspace/file associations. - LSP tests: lifecycle, edits/positions (UTF-16), stale diagnostics, completion, cancellation where supported, and multiple projects with different type systems. -- Required feature gates: all formatting, completion/navigation, and wizard - acceptance cases above pass before legacy-editor retirement. +- Required feature gates: continue validating formatting, completion/navigation, + and wizard acceptance cases above; distinguish automated checks from pending manual ones. - Performance: benchmark large generated `.impex` files and long unterminated quoted cells; set latency/memory budgets from baseline measurements. - Run `make test` and `make package`; install the produced p2 ZIP in a clean diff --git a/docs/internal/type-system-repository.md b/docs/internal/type-system-repository.md index 74b78457..602082c2 100644 --- a/docs/internal/type-system-repository.md +++ b/docs/internal/type-system-repository.md @@ -13,9 +13,8 @@ The previous SAP `YTypeSystem` usages were: | `ytypesystem/Activator.java` | Runtime type loading, type/name caches, attributes and loader locations | Delegates to shared snapshots; caches/runtime loading removed | | `ytypesystem/YTypeSystemBuilder.java` | Loaded platform classes and parsed items XML | Removed | | `ytypesystem/ExtendedYTypeSystem.java` | Subclassed SAP type system and reflected into private fields | Removed | -| `impexed/Activator.java` | Delegated completion and hyperlink data to the old Activator | Uses commons index directly | -| ImpEx completion processors | Requested types and qualifiers through the Activator | Retain their API, now backed by generated models | -| ImpEx hyperlink detector/link | Cached type names and decoded items.xml loader strings | Reads current names and opens the generated model source | +| Legacy ImpEx Activator/completion processors | Requested types and qualifiers through the Activator | Removed; the LSP workspace adapter supplies document-scoped shared snapshots | +| Legacy ImpEx hyperlink detector/link | Cached type names and decoded items.xml loader strings | Removed; LSP definitions resolve accessible generated-model source locations | | Beans type selection/label provider/generator | Used SAP composed types and attributes | Uses shared types and accessor Java types | | `tsv.extended/.../PlatformServiceImplHyeclipse.java` | Returns SAP `YTypeSystem` to the TSV library | Removed in the source-built TSV migration | | `tsv.extended/.../TSVExtendedYTypeSystem.java` | SAP subclass with private-field reflection | Removed in the source-built TSV migration | diff --git a/pom.xml b/pom.xml index 2b931dc7..b94aea2c 100644 --- a/pom.xml +++ b/pom.xml @@ -49,7 +49,6 @@ com.hybris.hyeclipse.commons com.hybris.hyeclipse.hac - com.hybris.hyeclipse.impexed com.hybris.hyeclipse.impex com.hybris.hyeclipse.impex.ls com.hybris.hyeclipse.impex.tests From 65d5442dfc8773b789530bb65548b2e0c5f7fcb3 Mon Sep 17 00:00:00 2001 From: Pawel Wolanski Date: Mon, 23 Nov 2026 12:34:34 +0100 Subject: [PATCH 08/25] docs: add documentation versioning policy Align documentation with plugin metadata and immutable release tags. Distinguish current Pages content from installed p2 versions. Fix navigation and links needed for strict documentation builds. --- docs/dev/development.md | 11 +++ docs/dev/impex/editor-replacement-plan.md | 5 +- docs/dev/versioning.md | 87 +++++++++++++++++++++++ docs/installation.md | 2 +- mkdocs.yml | 4 ++ 5 files changed, 106 insertions(+), 3 deletions(-) create mode 100644 docs/dev/versioning.md diff --git a/docs/dev/development.md b/docs/dev/development.md index 0470add3..46e5a971 100644 --- a/docs/dev/development.md +++ b/docs/dev/development.md @@ -6,6 +6,10 @@ The documentation site uses MkDocs with Material. `README.md` supplies the homep the remaining pages and images come from `docs/`. Do not maintain a separate `docs/index.md`. Navigation and site settings are in the root `mkdocs.yml`. +Documentation tracks plugin release tags rather than a separate version counter. +See [Documentation and plugin versioning](versioning.md) for update policy, +release alignment, and how to read documentation for an installed version. + From the repository root, use Python 3.13 and an isolated environment: ```bash @@ -158,6 +162,9 @@ Release notes are generated thanks to [gren](https://github.com/github-tools/git Follow these steps to prepare, build, and publish a new release: +Complete the [release documentation checklist](versioning.md#release-documentation-checklist) +before tagging so the tag includes documentation matching the delivered artifacts. + ### 1. Create a Release Branch Start from the latest `master` (or target development branch): ```bash @@ -230,6 +237,10 @@ together. Once merged into `master`, the Pages workflow publishes it at the stab `updates/latest/` URL without rebuilding or re-signing it. ### 6. Commit and Tag Release +Stage the reviewed `README.md`, `CHANGELOG.md`, and `docs/` changes alongside +the synchronized release metadata. Do not tag a release with its matching +documentation still uncommitted or add unrelated, unreviewed documentation files. + ```bash git add pom.xml */pom.xml */META-INF/MANIFEST.MF */feature.xml updatesite/neon/ git commit -m "chore(release): bump version to VERSION.RELEASE" diff --git a/docs/dev/impex/editor-replacement-plan.md b/docs/dev/impex/editor-replacement-plan.md index 531ead66..9d85ac0e 100644 --- a/docs/dev/impex/editor-replacement-plan.md +++ b/docs/dev/impex/editor-replacement-plan.md @@ -97,8 +97,9 @@ Inputs: - [ImpEx behavior notes](impex-docs.md): reference for lexical edge cases, not a complete formal language specification. Runtime-dependent claims require verification against the supported Commerce version. -- [TextMate grammar](../../../com.hybris.hyeclipse.impex/syntaxes/impex.tmLanguage.json): - canonical packaged grammar, still under migration. +- TextMate grammar at the repository-relative path + `com.hybris.hyeclipse.impex/syntaxes/impex.tmLanguage.json`, the canonical packaged + grammar still under migration. - Legacy editor, wizard, formatter, completion processors, and hyperlink classes, available in Git history before the cutover commit. diff --git a/docs/dev/versioning.md b/docs/dev/versioning.md new file mode 100644 index 00000000..a4da0e87 --- /dev/null +++ b/docs/dev/versioning.md @@ -0,0 +1,87 @@ +# Documentation and plugin versioning + +Documentation follows the plugin's Git history and release tags. There is no +independent documentation version number and no release-version selector on the +current MkDocs site. + +## Version sources + +| Item | Source of truth | Example | +| --- | --- | --- | +| Development version | Root and module `pom.xml` files | `22.11.1-SNAPSHOT` | +| Development bundle/feature version | `META-INF/MANIFEST.MF` and `feature.xml` | `22.11.1.qualifier` | +| Release version | Synchronized Maven, bundle, and feature metadata | `22.11.1.RELEASE` | +| Release tag | Git tag identifying the release source and documentation | `v22.11.1` | +| Installed/distributed version | p2 metadata and release assets | Consult the installed feature or release notes | +| Published documentation | Latest successful documentation deployment from `master` | May include unreleased changes | + +Examples illustrate the naming convention; they do not assign the next release. +Maintain the existing three-component version sequence. Do not derive a plugin +version automatically from today's date, the Java version, or the Eclipse target. + +Use the Tycho Versions plugin described in +[the release procedure](development.md#2-set-the-new-release-version) to update +Maven, bundle, and feature versions together. Do not change individual versions +with manual search-and-replace. Build qualifiers are not separate documentation +releases. + +## When to update documentation + +- Update behavior, setup, and migration documentation in the same change as the + implementation. Include user-visible changes in `CHANGELOG.md`. +- Mark features not yet present in a published artifact as **Unreleased**. State + **Available since X.Y.Z** only after that release has been published. +- Documentation corrections alone do not require a plugin version bump or a new + p2 repository. They can be published from `master` through the existing Pages workflow. +- For compatibility-affecting changes, document removed APIs/bundles, replacement + behavior, user actions, and known limitations. The maintainer chooses the next + plugin version; the numeric version alone is not a compatibility guarantee. + +For example, retiring the legacy ImpEx editor requires release notes explaining +the new default editor, possible reassociation/manual uninstallation, and any +remaining grammar or indexing limitations. Do not describe manual checks as +completed unless they were actually performed. + +## Release documentation checklist + +Before creating the release tag: + +1. Apply the selected plugin release version using the release procedure. +2. Review `README.md`, installation requirements, changed feature guides, and + migration notes against the actual release candidate—not just current source. +3. Convert applicable **Unreleased** changelog entries into the release section; + retain genuinely unreleased work under **Unreleased**. +4. Validate documentation using the commands in + [Documentation website](development.md#documentation-website), including the + strict MkDocs build and published-resource tests. +5. Include matching documentation and changelog changes in the source commit + referenced by the release tag. Publish the artifacts using the + [release procedure](development.md#releasing-a-new-version). + +After publication, prepare the next development `-SNAPSHOT` in a separate change. +Do not move or recreate an existing release tag to incorporate later documentation +fixes. Put corrections on the development branch and, when necessary, a dedicated +release-maintenance branch or a new release. + +## Read documentation for an installed release + +The public MkDocs site represents the latest deployed `master` documentation, +not necessarily the version offered by `updates/latest/`. Documentation deployment +does not build or release Java bundles; p2 publication uses the committed repository. +See [What is published](../installation.md#what-is-published). + +For version-specific source documentation, select the release tag on GitHub and +browse `README.md` and `docs/` in the repository that published the release. A fork's +tag may not exist in the upstream repository. Locally, inspect tagged files without +changing the working tree: + +```bash +VERSION=22.11.0 # replace with the installed release's tag version +git show "v${VERSION}:README.md" +git show "v${VERSION}:docs/installation.md" +``` + +Some older tags predate particular documentation pages. Use the README, changelog, +and documentation files that exist at that tag. Check the current site's corrections +and migration notes separately; do not treat newer instructions as evidence that an +older binary supports the same features. diff --git a/docs/installation.md b/docs/installation.md index f4c20820..653f11ca 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -33,7 +33,7 @@ The repository metadata determines the available plugin version. GitHub Pages serves the p2 metadata, feature JARs, and plugin JARs without modifying their bytes. Hosting does not sign artifacts or change their existing signatures. -See the [release process](dev/development.md#4-sign-deliverable-eclipse-artifacts) +See the [release process](dev/development.md#releasing-a-new-version) for signing requirements. The update URL is for Eclipse's installer, not a browsable documentation page. diff --git a/mkdocs.yml b/mkdocs.yml index dd248165..7fb9e222 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -61,6 +61,10 @@ nav: - Knowledge database: kb/info.md - Developer guide: - Development and releases: dev/development.md + - Documentation and plugin versioning: dev/versioning.md + - ImpEx: + - Language behavior: dev/impex/impex-docs.md + - Editor migration plan: dev/impex/editor-replacement-plan.md - Regression verification: dev/import-and-junit-verification.md - Project information: - Deprecations: deprecation/deprecation.md From d7695117416dd682472a9124108eae7d7d615423 Mon Sep 17 00:00:00 2001 From: Pawel Wolanski Date: Mon, 23 Nov 2026 13:16:35 +0100 Subject: [PATCH 09/25] feat(docs): add MkDocs versioned publication Retain immutable release snapshots with Mike and a Development selector. Preserve root links and canonical p2 bytes in one Pages artifact. Build tagged content with trusted tooling and persist generated history only from the protected deployment job. --- .github/workflows/docs.yml | 48 +++++++- .gitignore | 1 + docs/dev/development.md | 34 +++++- docs/dev/versioning.md | 53 ++++++-- docs/installation.md | 3 + mkdocs.yml | 7 ++ tools/docs/hooks.py | 17 ++- tools/docs/requirements.txt | 1 + tools/docs/resources.py | 41 +++++++ tools/docs/test_hooks.py | 15 ++- tools/docs/test_site.py | 33 +---- tools/docs/test_versioning.py | 185 ++++++++++++++++++++++++++++ tools/docs/versioned_site.py | 220 ++++++++++++++++++++++++++++++++++ 13 files changed, 606 insertions(+), 52 deletions(-) create mode 100644 tools/docs/resources.py create mode 100644 tools/docs/test_versioning.py create mode 100644 tools/docs/versioned_site.py diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index 8acd6f6c..af22e6d2 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -18,13 +18,21 @@ on: - 'updatesite/**' - 'mkdocs.yml' - '.github/workflows/docs.yml' + release: + types: [published] workflow_dispatch: + inputs: + release_tag: + description: 'Optional vX.Y.Z tag to archive; blank updates Development only' + required: false + default: '' + type: string permissions: contents: read concurrency: - group: docs-${{ github.workflow }}-${{ github.ref }} + group: docs-${{ github.workflow }}-${{ github.event_name == 'pull_request' && format('pr-{0}', github.event.pull_request.number) || 'publish' }} cancel-in-progress: ${{ github.event_name == 'pull_request' }} jobs: @@ -37,6 +45,8 @@ jobs: - uses: actions/checkout@v7 with: persist-credentials: false + fetch-depth: 0 + ref: ${{ github.event_name == 'release' && 'master' || github.ref }} - uses: actions/setup-python@v7 with: python-version: '3.13' @@ -48,26 +58,56 @@ jobs: run: python -m unittest discover -s tools/docs -p 'test_*.py' - name: Build documentation and validate Eclipse update site run: python -m mkdocs build --strict + - name: Assemble versioned documentation and canonical Eclipse update site + env: + RELEASE_TAG: ${{ github.event.release.tag_name || inputs.release_tag || '' }} + GIT_AUTHOR_NAME: github-actions[bot] + GIT_AUTHOR_EMAIL: 41898282+github-actions[bot]@users.noreply.github.com + GIT_COMMITTER_NAME: github-actions[bot] + GIT_COMMITTER_EMAIL: 41898282+github-actions[bot]@users.noreply.github.com + run: python tools/docs/versioned_site.py --release-tag "$RELEASE_TAG" --export-history + - name: Transfer generated documentation history to deployment job + if: (github.ref == 'refs/heads/master' && github.event_name != 'pull_request') || github.event_name == 'release' + uses: actions/upload-artifact@v4 + with: + name: docs-history + path: docs-history.bundle + if-no-files-found: error + retention-days: 1 - name: Configure Pages - if: github.ref == 'refs/heads/master' && github.event_name != 'pull_request' + if: (github.ref == 'refs/heads/master' && github.event_name != 'pull_request') || github.event_name == 'release' uses: actions/configure-pages@v6 - name: Upload Pages artifact - if: github.ref == 'refs/heads/master' && github.event_name != 'pull_request' + if: (github.ref == 'refs/heads/master' && github.event_name != 'pull_request') || github.event_name == 'release' uses: actions/upload-pages-artifact@v5 with: path: site deploy: - if: github.ref == 'refs/heads/master' && github.event_name != 'pull_request' + if: (github.ref == 'refs/heads/master' && github.event_name != 'pull_request') || github.event_name == 'release' needs: build runs-on: ubuntu-latest permissions: + contents: write pages: write id-token: write environment: name: github-pages url: ${{ steps.deployment.outputs.page_url }} steps: + - uses: actions/checkout@v7 + with: + ref: master + fetch-depth: 0 + persist-credentials: true + - uses: actions/download-artifact@v4 + with: + name: docs-history + path: ${{ runner.temp }}/docs-history + - name: Persist generated version archives without changing source branches + run: | + git fetch "$RUNNER_TEMP/docs-history/docs-history.bundle" docs-versions:refs/heads/docs-versions + git push origin refs/heads/docs-versions:refs/heads/docs-versions - name: Deploy GitHub Pages id: deployment uses: actions/deploy-pages@v5 diff --git a/.gitignore b/.gitignore index 90f3d7ca..0750aed2 100644 --- a/.gitignore +++ b/.gitignore @@ -9,5 +9,6 @@ .metals .vscode /site/ +/docs-history.bundle /.venv-docs/ __pycache__/ diff --git a/docs/dev/development.md b/docs/dev/development.md index 46e5a971..3ae7636f 100644 --- a/docs/dev/development.md +++ b/docs/dev/development.md @@ -34,14 +34,42 @@ External links are not checked by the strict build. ### GitHub Pages deployment In repository **Settings → Pages**, select **GitHub Actions** as the source. +Allow `master` and release tags matching `v*` in the `github-pages` environment's +deployment rules if that environment restricts branches/tags. The workflow still +rejects manual publication from other branches and validates release tag versions. The Documentation and Eclipse update site workflow validates pull requests without deploying them and publishes -documentation or `updatesite/` changes pushed to `master`. To rebuild manually, run the workflow from -the Actions tab with `master` selected. Other branches cannot deploy. +documentation or `updatesite/` changes pushed to `master`. Published GitHub releases also trigger +archiving of their tagged documentation. To rebuild or backfill a release, run the workflow from +the Actions tab with `master` selected; optionally provide `release_tag=vX.Y.Z`. +Manual runs on other branches cannot deploy. -The public site is https://sap.github.io/hybris-commerce-eclipse-plugin/. +The public site is https://sap.github.io/hybris-commerce-eclipse-plugin/; its root redirects to the latest working docs. The same deployment also hosts the Eclipse p2 repository at https://sap.github.io/hybris-commerce-eclipse-plugin/updates/latest/. +### Versioned documentation + +Mike stores generated snapshots on `docs-versions`; Material displays its version selector. +`latest` redirects to `development`, while release snapshots use full `X.Y.Z` directories. +See [Documentation and plugin versioning](versioning.md) for eligibility and archival policy. + +The build wrapper creates the combined Pages artifact at `site/`, validates its links, +and adds one byte-preserved installer repository at `/updates/latest/`. It never pushes +branches itself. CI exports `docs-history.bundle` and only the trusted deployment job +pushes generated history, without force-pushing or changing source branches. + +For local multi-version preview, activate the documentation environment and run: + +```bash +python tools/docs/versioned_site.py +mike serve --branch docs-versions +``` + +These commands create local history commits but do not push or deploy. `mike serve` +previews documentation history only; the canonical p2 files are added to the assembled +`site/` artifact. `mkdocs serve` remains the live, single-version source preview. +Do not use `mike deploy --push` as a separate Pages publisher: that would omit the installer files. + ### Eclipse p2 hosting The post-build hook copies the committed `updatesite/latest` repository (currently a diff --git a/docs/dev/versioning.md b/docs/dev/versioning.md index a4da0e87..fda2a65f 100644 --- a/docs/dev/versioning.md +++ b/docs/dev/versioning.md @@ -1,8 +1,45 @@ # Documentation and plugin versioning -Documentation follows the plugin's Git history and release tags. There is no -independent documentation version number and no release-version selector on the -current MkDocs site. +Documentation follows the plugin's Git history and release tags. MkDocs/Material +uses Mike to provide a version selector. There is no independent documentation +version counter: release directories use the full plugin version, such as `22.11.0`. + +## Published documentation versions + +| URL suffix | Content | +| --- | --- | +| `/` | Redirect to the latest working documentation | +| `/latest/` | Redirect alias for Development | +| `/development/` | Latest successful `master` documentation build | +| `/X.Y.Z/` | Immutable documentation snapshot from release tag `vX.Y.Z` | +| `/updates/latest/` | Canonical Eclipse installer repository, always copied from committed `master` p2 files | + +The selector lists archived releases and **Development**. Development may describe +unreleased changes; it is not a claim that the installer repository offers those +features. Each release remains canonical to its own version directory. + +Generated HTML and `versions.json` are retained on the reserved `docs-versions` +branch. The existing Pages workflow publishes versioned documentation and the +canonical p2 repository together; do not publish a docs-only artifact separately. + +## Archive a release + +- Publishing a GitHub release runs the documentation workflow against current + trusted `master` tooling and archives the release tag's Markdown, README, and navigation. +- To backfill an existing release, run **Documentation and Eclipse update site** + from the Actions tab with `master` selected and `release_tag` set to `vX.Y.Z`. + Leave the input blank to update Development only. +- Eligible tags must contain MkDocs sources and `pom.xml` version `X.Y.Z.RELEASE`. + Some older tags predate MkDocs; inspect their source documentation through Git instead. +- Existing release snapshots are not rebuilt. If a tag has been moved to another + commit, the workflow refuses to replace its recorded snapshot. +- Tag builds never publish that tag's p2 files over `/updates/latest/`. The installer + bytes still come from `master`, even when release documentation is added. + +Only the trusted Pages deployment job has permission to push generated history. +Pull requests and manual runs on other branches validate without publishing. +For a fork, configure `mkdocs.yml`'s `site_url` and `repo_url` for the actual +publishing repository so canonical and tagged source links point to the correct site. ## Version sources @@ -13,7 +50,8 @@ current MkDocs site. | Release version | Synchronized Maven, bundle, and feature metadata | `22.11.1.RELEASE` | | Release tag | Git tag identifying the release source and documentation | `v22.11.1` | | Installed/distributed version | p2 metadata and release assets | Consult the installed feature or release notes | -| Published documentation | Latest successful documentation deployment from `master` | May include unreleased changes | +| Development documentation | Latest successful deployment from `master` | May include unreleased changes | +| Archived documentation | Recorded release-tag source commit | `/22.11.0/` after that tag is archived | Examples illustrate the naming convention; they do not assign the next release. Maintain the existing three-component version sequence. Do not derive a plugin @@ -65,12 +103,13 @@ release-maintenance branch or a new release. ## Read documentation for an installed release -The public MkDocs site represents the latest deployed `master` documentation, -not necessarily the version offered by `updates/latest/`. Documentation deployment +The root/latest MkDocs pages represent the latest deployed `master` documentation, +not necessarily the version offered by `updates/latest/`. Choose the installed +version from the selector for an archived snapshot. Documentation deployment does not build or release Java bundles; p2 publication uses the committed repository. See [What is published](../installation.md#what-is-published). -For version-specific source documentation, select the release tag on GitHub and +For releases not yet archived, or version-specific source documentation, select the release tag on GitHub and browse `README.md` and `docs/` in the repository that published the release. A fork's tag may not exist in the upstream repository. Locally, inspect tagged files without changing the working tree: diff --git a/docs/installation.md b/docs/installation.md index 653f11ca..b61d5eb6 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -21,6 +21,9 @@ To update an existing installation, use **Help → Check for Updates** with this ## What is published +The documentation version selector changes documentation pages only. The installer +URL above remains stable and is independent of selected documentation releases. + The hosted repository mirrors the committed `updatesite/latest` repository on `master`. That path currently points to `updatesite/neon`; the directory name is historical and does not by itself determine Eclipse compatibility. Consult the release notes and diff --git a/mkdocs.yml b/mkdocs.yml index 7fb9e222..217fa716 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -6,6 +6,7 @@ repo_name: SAP/hybris-commerce-eclipse-plugin edit_uri: edit/master/docs/ docs_dir: docs site_dir: site +remote_branch: docs-versions theme: name: material @@ -19,6 +20,12 @@ theme: plugins: - search + - mike: + alias_type: redirect + +extra: + version: + provider: mike hooks: - tools/docs/hooks.py diff --git a/tools/docs/hooks.py b/tools/docs/hooks.py index c24fe86e..a5287d40 100644 --- a/tools/docs/hooks.py +++ b/tools/docs/hooks.py @@ -4,6 +4,7 @@ import hashlib import lzma +import os import re import shutil import xml.etree.ElementTree as ET @@ -14,26 +15,27 @@ from mkdocs.structure.files import File -def homepage_markdown(markdown, repo_url): +def homepage_markdown(markdown, repo_url, source_ref="master"): """Rebase the README's inline links from the repository root to docs/.""" # Keep the directory browser on GitHub; it is not a documentation page. - markdown = markdown.replace("](docs/)", f"]({repo_url}/tree/master/docs/)") + markdown = markdown.replace("](docs/)", f"]({repo_url}/tree/{source_ref}/docs/)") # Rebase inline Markdown destinations without changing absolute URLs. markdown = markdown.replace("](docs/", "](") for filename in ("CODE_OF_CONDUCT.md", "CONTRIBUTING.md", "LICENSE"): markdown = markdown.replace( - f"]({filename})", f"]({repo_url}/blob/master/{filename})" + f"]({filename})", f"]({repo_url}/blob/{source_ref}/{filename})" ) return markdown def on_files(files, config): - root = Path(config.config_file_path).parent + root = Path(os.environ.get("COMMERCE_DOCS_SOURCE_ROOT", Path(config.config_file_path).parent)) + source_ref = os.environ.get("COMMERCE_DOCS_SOURCE_REF", "master") markdown = homepage_markdown( - (root / "README.md").read_text(encoding="utf-8"), config.repo_url.rstrip("/") + (root / "README.md").read_text(encoding="utf-8"), config.repo_url.rstrip("/"), source_ref ) homepage = File.generated(config, "index.md", content=markdown) - homepage.edit_uri = f"{config.repo_url.rstrip('/')}/edit/master/README.md" + homepage.edit_uri = f"{config.repo_url.rstrip('/')}/edit/master/README.md" if source_ref == "master" else None files.append(homepage) return files @@ -100,6 +102,9 @@ def publish_update_site(source, destination): def on_post_build(config): + # Version snapshots contain docs only; the final Pages artifact adds one canonical p2 repository. + if os.environ.get("COMMERCE_DOCS_VERSION_BUILD") == "1": + return root = Path(config.config_file_path).parent try: publish_update_site(root / "updatesite/latest", Path(config.site_dir) / "updates/latest") diff --git a/tools/docs/requirements.txt b/tools/docs/requirements.txt index b9689135..654ff4a2 100644 --- a/tools/docs/requirements.txt +++ b/tools/docs/requirements.txt @@ -2,3 +2,4 @@ # SPDX-License-Identifier: Apache-2.0 mkdocs==1.6.1 mkdocs-material==9.8.1 +mike==2.2.0 diff --git a/tools/docs/resources.py b/tools/docs/resources.py new file mode 100644 index 00000000..db16b896 --- /dev/null +++ b/tools/docs/resources.py @@ -0,0 +1,41 @@ +# SPDX-FileCopyrightText: 2026 SAP SE or an SAP affiliate company and contributors +# SPDX-License-Identifier: Apache-2.0 +"""Validate local links and assets in the final Pages artifact, including redirects.""" + +from html.parser import HTMLParser +from pathlib import Path +from urllib.parse import unquote, urlsplit + + +class ResourceParser(HTMLParser): + def __init__(self): + super().__init__() + self.urls = [] + + def handle_starttag(self, tag, attrs): + for name, value in attrs: + if name in ("src", "href") and value: + self.urls.append(value) + + +def validate_site_resources(site, site_url): + site = Path(site).resolve() + prefix = urlsplit(site_url).path + for page in site.rglob("*.html"): + parser = ResourceParser() + parser.feed(page.read_text(encoding="utf-8")) + for url in parser.urls: + parsed = urlsplit(url) + if parsed.scheme or parsed.netloc or not parsed.path: + continue + path = unquote(parsed.path) + if path.startswith("/"): + if not path.startswith(prefix): + raise ValueError(f"URL escapes project prefix in {page.relative_to(site)}: {url}") + target = site / path[len(prefix):] + else: + target = page.parent / path + if target.is_dir(): + target /= "index.html" + if not target.resolve().is_relative_to(site) or not target.is_file(): + raise ValueError(f"Missing published resource in {page.relative_to(site)}: {url}") diff --git a/tools/docs/test_hooks.py b/tools/docs/test_hooks.py index a85667be..f0286ce0 100644 --- a/tools/docs/test_hooks.py +++ b/tools/docs/test_hooks.py @@ -3,15 +3,28 @@ """Regression tests for the generated documentation homepage.""" import unittest +from unittest.mock import patch from pathlib import Path from mkdocs.config import load_config from mkdocs.structure.files import Files -from hooks import homepage_markdown +from hooks import homepage_markdown, on_post_build class HomepageTest(unittest.TestCase): + def test_release_source_links_use_the_tag(self): + self.assertEqual( + "[Sources](https://example.com/repo/tree/v1.2.3/docs/) [License](https://example.com/repo/blob/v1.2.3/LICENSE)", + homepage_markdown("[Sources](docs/) [License](LICENSE)", "https://example.com/repo", "v1.2.3"), + ) + + def test_version_snapshot_does_not_copy_the_installer_repository(self): + with patch.dict("os.environ", {"COMMERCE_DOCS_VERSION_BUILD": "1"}): + with patch("hooks.publish_update_site") as publish: + on_post_build(None) + publish.assert_not_called() + def test_document_links_preserve_fragments(self): self.assertEqual( "[Import](importer/importer.md#features)", diff --git a/tools/docs/test_site.py b/tools/docs/test_site.py index 3fe7ffcb..b4801103 100644 --- a/tools/docs/test_site.py +++ b/tools/docs/test_site.py @@ -5,23 +5,11 @@ import json import tempfile import unittest -from html.parser import HTMLParser from pathlib import Path -from urllib.parse import unquote, urlsplit from mkdocs.commands.build import build from mkdocs.config import load_config - - -class ResourceParser(HTMLParser): - def __init__(self): - super().__init__() - self.urls = [] - - def handle_starttag(self, tag, attrs): - for name, value in attrs: - if name in ("src", "href") and value: - self.urls.append(value) +from resources import validate_site_resources class SiteTest(unittest.TestCase): @@ -31,24 +19,7 @@ def test_published_resources(self): site = Path(directory) / "site" config = load_config(str(root / "mkdocs.yml"), site_dir=str(site), strict=True) build(config) - prefix = urlsplit(config.site_url).path - for page in site.rglob("*.html"): - parser = ResourceParser() - parser.feed(page.read_text(encoding="utf-8")) - for url in parser.urls: - with self.subTest(page=str(page.relative_to(site)), url=url): - parsed = urlsplit(url) - if parsed.scheme or parsed.netloc or not parsed.path: - continue - path = unquote(parsed.path) - if path.startswith("/"): - self.assertTrue(path.startswith(prefix), "URL escapes project prefix") - target = site / path[len(prefix):] - else: - target = page.parent / path - if target.is_dir(): - target = target / "index.html" - self.assertTrue(target.is_file(), f"Missing published resource: {target}") + validate_site_resources(site, config.site_url) for image in (root / "docs").rglob("*"): if image.suffix in (".gif", ".png"): diff --git a/tools/docs/test_versioning.py b/tools/docs/test_versioning.py new file mode 100644 index 00000000..1f5cf746 --- /dev/null +++ b/tools/docs/test_versioning.py @@ -0,0 +1,185 @@ +# SPDX-FileCopyrightText: 2026 SAP SE or an SAP affiliate company and contributors +# SPDX-License-Identifier: Apache-2.0 +"""Exercise actual Mike builds in an isolated Git repository, never the user's branches.""" + +import hashlib +import json +import shutil +import tempfile +import unittest +import xml.etree.ElementTree as ET +from pathlib import Path +from urllib.parse import unquote, urlsplit + +import yaml + +from resources import ResourceParser, validate_site_resources +from versioned_site import HISTORY_BRANCH, build_site, deployment_config, git, history_versions + + +class VersioningTest(unittest.TestCase): + def setUp(self): + self.temporary = tempfile.TemporaryDirectory(prefix="commerce-versioning-") + self.addCleanup(self.temporary.cleanup) + self.root = Path(self.temporary.name) + git(self.root, "init", "-b", "master") + git(self.root, "config", "user.name", "Documentation test") + git(self.root, "config", "user.email", "docs-test@example.invalid") + (self.root / "docs").mkdir() + (self.root / "tools/docs").mkdir(parents=True) + original = Path(__file__).resolve().parents[2] + shutil.copyfile(original / "tools/docs/hooks.py", self.root / "tools/docs/hooks.py") + (self.root / ".gitignore").write_text("site/\ndocs-history.bundle\n", encoding="utf-8") + self.config = { + "site_name": "Versioning test", "site_url": "https://example.com/project/", + "repo_url": "https://github.com/example/repository", "docs_dir": "docs", "site_dir": "site", + "theme": {"name": "material", "font": False, "features": ["content.action.edit"]}, + "hooks": ["tools/docs/hooks.py"], "plugins": ["search"], + "watch": ["README.md", "tools/docs", "updatesite"], + "nav": [{"Home": "index.md"}, {"Install": "installation.md"}], + "validation": {"nav": {"omitted_files": "warn"}, "links": {"not_found": "warn"}}, + } + (self.root / "mkdocs.yml").write_text(yaml.safe_dump(self.config), encoding="utf-8") + self.write_source("Released documentation", "1.2.3.RELEASE") + self.write_repository(b"release artifact") + self.commit() + git(self.root, "tag", "v1.2.3") + self.release_sha = git(self.root, "rev-parse", "HEAD").stdout.decode().strip() + self.write_source("Development documentation", "1.2.4-SNAPSHOT") + self.write_repository(b"current master artifact") + self.commit() + + def write_source(self, title, version): + (self.root / "README.md").write_text(f"# {title}\n[Install](docs/installation.md)\n[License](LICENSE)\n", encoding="utf-8") + (self.root / "docs/installation.md").write_text(f"# Installation\n{title}\n", encoding="utf-8") + (self.root / "pom.xml").write_text( + f'{version}', encoding="utf-8" + ) + + def write_repository(self, artifact): + source = self.root / "updatesite/latest" + (source / "plugins").mkdir(parents=True, exist_ok=True) + (source / "plugins/example.bundle_1.2.3.jar").write_bytes(artifact) + content = ET.fromstring('') + artifacts = ET.fromstring('') + props = artifacts.find("./artifacts/artifact/properties") + ET.SubElement(props, "property", name="download.size", value=str(len(artifact))) + ET.SubElement(props, "property", name="download.checksum.sha-256", value=hashlib.sha256(artifact).hexdigest()) + (source / "content.xml").write_bytes(ET.tostring(content)) + (source / "artifacts.xml").write_bytes(ET.tostring(artifacts)) + (source / "p2.index").write_text("version=1\n", encoding="utf-8") + + def commit(self): + git(self.root, "add", ".") + git(self.root, "commit", "-m", "Documentation fixture") + + def test_version_archives_selector_redirects_p2_and_history_round_trip(self): + source_head = git(self.root, "rev-parse", "HEAD").stdout + output = build_site(self.root, "v1.2.3", export_history=True) + versions = json.loads((output / "versions.json").read_text()) + release = next(item for item in versions if item["version"] == "1.2.3") + development = next(item for item in versions if item["version"] == "development") + self.assertEqual(self.release_sha, release["properties"]["source_commit"]) + self.assertEqual(["latest"], development["aliases"]) + released_html = (output / "1.2.3/index.html").read_bytes() + self.assertIn(b"Released documentation", released_html) + self.assertIn(b"/blob/v1.2.3/LICENSE", released_html) + self.assertIn(b"Development documentation", (output / "development/index.html").read_bytes()) + self.assertIn(b'"version"', (output / "development/index.html").read_bytes()) + self.assertTrue((output / "latest/installation/index.html").exists()) + self.assertIn("latest", (output / "index.html").read_text()) + self.assertIn("latest/installation/index.html", (output / "installation/index.html").read_text()) + self.assertEqual(b"current master artifact", (output / "updates/latest/plugins/example.bundle_1.2.3.jar").read_bytes()) + self.assertFalse((output / "1.2.3/updates").exists()) + self.assertFalse((output / "development/updates").exists()) + self.assertFalse(any(path.is_symlink() for path in output.rglob("*"))) + for page in output.rglob("*.html"): + parser = ResourceParser() + parser.feed(page.read_text(encoding="utf-8")) + for url in parser.urls: + parsed = urlsplit(url) + if parsed.scheme or parsed.netloc or not parsed.path: + continue + path = unquote(parsed.path) + if path.startswith("/"): + self.assertTrue(path.startswith("/project/"), (page, url)) + target = output / path[len("/project/"):] + else: + target = page.parent / path + if target.is_dir(): + target /= "index.html" + self.assertTrue(target.is_file(), (page, url)) + self.assertEqual(source_head, git(self.root, "rev-parse", "HEAD").stdout) + self.assertEqual("master", git(self.root, "branch", "--show-current").stdout.decode().strip()) + self.assertTrue((self.root / "docs-history.bundle").is_file()) + restored = self.root / "restored" + restored.mkdir() + git(restored, "init") + git(restored, "fetch", str(self.root / "docs-history.bundle"), f"{HISTORY_BRANCH}:refs/heads/{HISTORY_BRANCH}") + self.assertEqual(history_versions(self.root), history_versions(restored)) + shutil.rmtree(restored) + self.write_source("New development documentation", "1.2.4-SNAPSHOT") + self.commit() + build_site(self.root, "v1.2.3") + self.assertEqual(released_html, (output / "1.2.3/index.html").read_bytes()) + self.assertIn(b"New development documentation", (output / "development/index.html").read_bytes()) + + def test_invalid_release_and_dirty_export_do_not_modify_history(self): + with self.assertRaisesRegex(ValueError, "vX.Y.Z"): + build_site(self.root, "../master") + git(self.root, "tag", "v1.2.4") + with self.assertRaisesRegex(ValueError, "does not identify"): + build_site(self.root, "v1.2.4") + self.assertNotEqual(0, git(self.root, "rev-parse", "--verify", HISTORY_BRANCH, check=False).returncode) + (self.root / "docs/uncommitted.md").write_text("Unreviewed content") + with self.assertRaisesRegex(ValueError, "Commit documentation"): + build_site(self.root, export_history=True) + + def test_archived_release_cannot_be_overwritten_by_a_moved_tag(self): + build_site(self.root, "v1.2.3") + before = git(self.root, "rev-parse", HISTORY_BRANCH).stdout + self.write_source("Moved release source", "1.2.3.RELEASE") + self.commit() + git(self.root, "tag", "-f", "v1.2.3") + with self.assertRaisesRegex(ValueError, "Immutable"): + build_site(self.root, "v1.2.3") + self.assertEqual(before, git(self.root, "rev-parse", HISTORY_BRANCH).stdout) + + def test_artifact_validation_rejects_missing_and_prefix_escaping_resources(self): + site = self.root / "site" + site.mkdir() + page = site / "index.html" + page.write_text('', encoding="utf-8") + with self.assertRaisesRegex(ValueError, "escapes project prefix"): + validate_site_resources(site, self.config["site_url"]) + page.write_text('', encoding="utf-8") + with self.assertRaisesRegex(ValueError, "Missing published resource"): + validate_site_resources(site, self.config["site_url"]) + + def test_snapshot_config_rejects_outside_sources_and_untrusted_hooks(self): + source = dict(self.config, docs_dir="../outside") + with self.assertRaisesRegex(ValueError, "inside"): + deployment_config(self.config, source, self.root, self.root / "tools/docs/hooks.py", self.root / "build", "v1.2.3") + source = dict(self.config, hooks=["unsafe.py"], plugins=["unsafe"]) + config = deployment_config(self.config, source, self.root, self.root / "tools/docs/hooks.py", self.root / "build", "v1.2.3") + self.assertEqual([str(self.root / "tools/docs/hooks.py")], config["hooks"]) + self.assertEqual("search", config["plugins"][0]) + self.assertNotIn("unsafe", str(config["plugins"])) + self.assertEqual("", config["edit_uri"]) + + def test_workflow_only_pushes_history_from_the_trusted_deployment_job(self): + root = Path(__file__).resolve().parents[2] + workflow = yaml.load((root / ".github/workflows/docs.yml").read_text(), Loader=yaml.BaseLoader) + self.assertEqual("read", workflow["jobs"]["build"]["permissions"]["contents"]) + self.assertEqual("write", workflow["jobs"]["deploy"]["permissions"]["contents"]) + self.assertIn("github.ref == 'refs/heads/master'", workflow["jobs"]["deploy"]["if"]) + self.assertIn("github.event_name == 'release'", workflow["jobs"]["deploy"]["if"]) + build_commands = "\n".join(step.get("run", "") for step in workflow["jobs"]["build"]["steps"]) + self.assertNotIn("git push", build_commands) + deploy_commands = "\n".join(step.get("run", "") for step in workflow["jobs"]["deploy"]["steps"]) + self.assertIn("refs/heads/docs-versions:refs/heads/docs-versions", deploy_commands) + self.assertNotIn("--force", deploy_commands) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/docs/versioned_site.py b/tools/docs/versioned_site.py new file mode 100644 index 00000000..a37a7386 --- /dev/null +++ b/tools/docs/versioned_site.py @@ -0,0 +1,220 @@ +# SPDX-FileCopyrightText: 2026 SAP SE or an SAP affiliate company and contributors +# SPDX-License-Identifier: Apache-2.0 +"""Build Mike documentation history plus one canonical, byte-preserved p2 repository. + +Only the generated docs-versions branch is changed. This tool never pushes Git +branches; CI exports a bundle and pushes it from the trusted deployment job. +""" + +import argparse +import copy +import html +import io +import json +import os +import posixpath +import re +import shutil +import subprocess +import sys +import tarfile +import tempfile +import xml.etree.ElementTree as ET +from pathlib import Path + +import yaml + +from hooks import publish_update_site +from resources import validate_site_resources + + +HISTORY_BRANCH = "docs-versions" +DEVELOPMENT_VERSION = "development" +LATEST_ALIAS = "latest" +RELEASE_TAG = re.compile(r"v(\d+\.\d+\.\d+)\Z") + + +def git(root, *args, check=True): + return subprocess.run( + ["git", *args], cwd=root, check=check, stdout=subprocess.PIPE, stderr=subprocess.PIPE + ) + + +def history_versions(root): + for ref in (HISTORY_BRANCH, f"origin/{HISTORY_BRANCH}"): + if git(root, "rev-parse", "--verify", ref, check=False).returncode: + continue + result = git(root, "show", f"{ref}:versions.json", check=False) + if result.returncode: + raise ValueError(f"{ref} exists but is not a Mike documentation-history branch") + versions = json.loads(result.stdout) + if not isinstance(versions, list): + raise ValueError("Invalid documentation version metadata") + return versions + return [] + + +def source_links(value, source_ref): + if isinstance(value, str): + return value.replace("/blob/master/", f"/blob/{source_ref}/").replace( + "/tree/master/", f"/tree/{source_ref}/" + ) + if isinstance(value, list): + return [source_links(item, source_ref) for item in value] + if isinstance(value, dict): + return {key: source_links(item, source_ref) for key, item in value.items()} + return value + + +def deployment_config(base, source, source_root, trusted_hook, build_directory, source_ref): + config = copy.deepcopy(source) + docs = Path(config.get("docs_dir", "docs")) + if docs.is_absolute() or not (source_root / docs).resolve().is_relative_to(source_root.resolve()): + raise ValueError("Documentation sources must stay inside the source snapshot") + if not (source_root / docs).is_dir(): + raise ValueError("Source snapshot has no documentation directory") + config["docs_dir"] = str((source_root / docs).resolve()) + config["site_dir"] = str(build_directory) + # Snapshot configurations live in a temporary directory, not the live-preview project root. + config["watch"] = [] + config["site_url"] = base["site_url"] + config["repo_url"] = base["repo_url"] + config["theme"] = copy.deepcopy(base["theme"]) + config["plugins"] = ["search", {"mike": {"alias_type": "redirect"}}] + config["hooks"] = [str(trusted_hook)] + config["markdown_extensions"] = copy.deepcopy(base.get("markdown_extensions", [])) + config["validation"] = copy.deepcopy(base.get("validation", {})) + config["strict"] = True + config["remote_branch"] = HISTORY_BRANCH + config.setdefault("extra", {})["version"] = {"provider": "mike"} + if source_ref != "master": + config["edit_uri"] = "" + config["theme"]["features"] = [ + item for item in config["theme"].get("features", []) if item != "content.action.edit" + ] + config = source_links(config, source_ref) + return config + + +def mike(root, config_path, source_root, source_ref, *args): + env = os.environ.copy() + # Mike launches the mkdocs console script; keep both commands in this Python environment. + env["PATH"] = str(Path(sys.executable).parent) + os.pathsep + env.get("PATH", "") + env.update( + COMMERCE_DOCS_VERSION_BUILD="1", + COMMERCE_DOCS_SOURCE_ROOT=str(source_root), + COMMERCE_DOCS_SOURCE_REF=source_ref, + ) + subprocess.run( + [sys.executable, "-c", "from mike.driver import main\nmain()", *args, + "--branch", HISTORY_BRANCH, "--config-file", str(config_path)], + cwd=root, env=env, check=True, + ) + + +def release_source(root, tag, destination): + match = RELEASE_TAG.fullmatch(tag) + if not match: + raise ValueError("Release documentation requires a tag named vX.Y.Z") + sha = git(root, "rev-parse", "--verify", f"refs/tags/{tag}^{{commit}}").stdout.decode().strip() + archive = git(root, "archive", "--format=tar", tag, "README.md", "docs", "mkdocs.yml", "pom.xml") + with tarfile.open(fileobj=io.BytesIO(archive.stdout)) as files: + files.extractall(destination, filter="data") + version = match.group(1) + pom = ET.parse(destination / "pom.xml").getroot() + actual = pom.findtext("{http://maven.apache.org/POM/4.0.0}version") + if actual != f"{version}.RELEASE": + raise ValueError(f"Tag {tag} does not identify plugin version {version}.RELEASE") + return version, sha + + +def write_legacy_redirects(output): + """Keep previous unversioned page URLs working without touching archived files.""" + for page in (output / DEVELOPMENT_VERSION).rglob("*.html"): + relative = page.relative_to(output / DEVELOPMENT_VERSION) + destination = output / relative + if destination.exists(): + continue + target = posixpath.relpath(f"{LATEST_ALIAS}/{relative.as_posix()}", relative.parent.as_posix()) + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_text( + '' + f'' + f'Latest documentation' + '', + encoding="utf-8", + ) + + +def build_site(root, release_tag="", export_history=False): + root = Path(root).resolve() + if export_history: + changed = git(root, "status", "--porcelain", "--", "README.md", "docs", "mkdocs.yml", + "tools/docs", "updatesite").stdout + if changed: + raise ValueError("Commit documentation and tooling changes before exporting publication history") + base = yaml.safe_load((root / "mkdocs.yml").read_text(encoding="utf-8")) + hook = (root / "tools/docs/hooks.py").resolve() + versions = history_versions(root) + with tempfile.TemporaryDirectory(prefix="commerce-versioned-docs-") as temporary: + directory = Path(temporary) + release = None + # Validate release input before modifying documentation history. + if release_tag: + source_root = directory / "release" + source_root.mkdir() + version, sha = release_source(root, release_tag, source_root) + existing = next((item for item in versions if item["version"] == version), None) + if existing and existing.get("properties", {}).get("source_commit") != sha: + raise ValueError(f"Immutable documentation snapshot {version} has different source provenance") + release = (source_root, version, sha, existing) + development = deployment_config(base, base, root, hook, directory / "development-build", "master") + development_config = directory / "development.yml" + development_config.write_text(yaml.safe_dump(development, sort_keys=False), encoding="utf-8") + sha = git(root, "rev-parse", "HEAD").stdout.decode().strip() + mike(root, development_config, root, "master", "deploy", "--update-aliases", "--alias-type", "redirect", + "--title", "Development", "--prop-set-string", f"source_commit={sha}", + "--prop-set-string", "source_ref=master", DEVELOPMENT_VERSION, LATEST_ALIAS) + if release and not release[3]: + source_root, version, sha, unused_existing = release + source = yaml.safe_load((source_root / "mkdocs.yml").read_text(encoding="utf-8")) + config = deployment_config(base, source, source_root, hook, directory / "release-build", release_tag) + config_path = directory / "release.yml" + config_path.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8") + mike(root, config_path, source_root, release_tag, "deploy", "--alias-type", "redirect", + "--prop-set-string", f"source_commit={sha}", "--prop-set-string", f"source_ref={release_tag}", version) + mike(root, development_config, root, "master", "set-default", LATEST_ALIAS) + output = root / "site" + if output.exists(): + shutil.rmtree(output) + output.mkdir() + archive = git(root, "archive", "--format=tar", HISTORY_BRANCH) + with tarfile.open(fileobj=io.BytesIO(archive.stdout)) as files: + files.extractall(output, filter="data") + if any(path.is_symlink() for path in output.rglob("*")): + raise ValueError("Documentation history must use redirect aliases, not symlinks") + write_legacy_redirects(output) + # Always use the checked-out master repository, never a release snapshot's p2 bytes. + publish_update_site(root / "updatesite/latest", output / "updates/latest") + validate_site_resources(output, base["site_url"]) + if export_history: + bundle = root / "docs-history.bundle" + if bundle.exists(): + bundle.unlink() + git(root, "bundle", "create", str(bundle), HISTORY_BRANCH) + return output + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--release-tag", default="", help="Optional immutable vX.Y.Z release snapshot") + parser.add_argument("--export-history", action="store_true", help="Write docs-history.bundle for trusted CI publication") + args = parser.parse_args() + build_site(Path(__file__).resolve().parents[2], args.release_tag, args.export_history) + + +if __name__ == "__main__": + main() From 666d2e87fe29745ec9d9b75986674246fef6fa5d Mon Sep 17 00:00:00 2001 From: Pawel Wolanski Date: Mon, 23 Nov 2026 13:37:40 +0100 Subject: [PATCH 10/25] docs: configure personal fork Pages URLs --- README.md | 6 +++--- docs/dev/development.md | 4 ++-- docs/installation.md | 2 +- mkdocs.yml | 12 ++++++------ 4 files changed, 12 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 57c3c812..d67cccaf 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,7 @@ Plugin releases are backward compatible with IDE versions at least 6 months old Documentation ------------- -Read the [project documentation](https://sap.github.io/hybris-commerce-eclipse-plugin/) +Read the [project documentation](https://mikolayek.github.io/hybris-commerce-eclipse-plugin/) for user guides, troubleshooting, and developer documentation. The documentation sources are maintained in this README and [docs/](docs/). Contributing & Code of Conduct @@ -47,10 +47,10 @@ Download & Installation This GitHub repository is for managing the source code of the plugin. To install the plugin visit the [Eclipse Marketplace](https://marketplace.eclipse.org/content/sap-hybris-commerce-development-tools-eclipse). -Alternatively, add `https://sap.github.io/hybris-commerce-eclipse-plugin/updates/latest/` +Alternatively, add `https://mikolayek.github.io/hybris-commerce-eclipse-plugin/updates/latest/` in Eclipse under **Help → Install New Software…**. See the [installation guide](docs/installation.md) for details and the hosted release policy. -For usage and development guidance, see the [project documentation](https://sap.github.io/hybris-commerce-eclipse-plugin/). +For usage and development guidance, see the [project documentation](https://mikolayek.github.io/hybris-commerce-eclipse-plugin/). Compile and Install From Source ------------------------------- diff --git a/docs/dev/development.md b/docs/dev/development.md index 3ae7636f..05a1ba35 100644 --- a/docs/dev/development.md +++ b/docs/dev/development.md @@ -43,9 +43,9 @@ archiving of their tagged documentation. To rebuild or backfill a release, run t the Actions tab with `master` selected; optionally provide `release_tag=vX.Y.Z`. Manual runs on other branches cannot deploy. -The public site is https://sap.github.io/hybris-commerce-eclipse-plugin/; its root redirects to the latest working docs. +The public site is https://mikolayek.github.io/hybris-commerce-eclipse-plugin/; its root redirects to the latest working docs. The same deployment also hosts the Eclipse p2 repository at -https://sap.github.io/hybris-commerce-eclipse-plugin/updates/latest/. +https://mikolayek.github.io/hybris-commerce-eclipse-plugin/updates/latest/. ### Versioned documentation diff --git a/docs/installation.md b/docs/installation.md index b61d5eb6..2042e4ec 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -5,7 +5,7 @@ Install the plugin through the or use the hosted Eclipse p2 repository: ```text -https://sap.github.io/hybris-commerce-eclipse-plugin/updates/latest/ +https://mikolayek.github.io/hybris-commerce-eclipse-plugin/updates/latest/ ``` ## Install from the update site diff --git a/mkdocs.yml b/mkdocs.yml index 217fa716..774b11da 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -1,8 +1,8 @@ site_name: Eclipse Plugin for SAP Commerce site_description: User and developer documentation for the SAP Commerce Eclipse plugin. -site_url: https://sap.github.io/hybris-commerce-eclipse-plugin/ -repo_url: https://github.com/SAP/hybris-commerce-eclipse-plugin -repo_name: SAP/hybris-commerce-eclipse-plugin +site_url: https://mikolayek.github.io/hybris-commerce-eclipse-plugin/ +repo_url: https://github.com/mikolayek/hybris-commerce-eclipse-plugin +repo_name: mikolayek/hybris-commerce-eclipse-plugin edit_uri: edit/master/docs/ docs_dir: docs site_dir: site @@ -75,6 +75,6 @@ nav: - Regression verification: dev/import-and-junit-verification.md - Project information: - Deprecations: deprecation/deprecation.md - - Contributing: https://github.com/SAP/hybris-commerce-eclipse-plugin/blob/master/CONTRIBUTING.md - - Code of conduct: https://github.com/SAP/hybris-commerce-eclipse-plugin/blob/master/CODE_OF_CONDUCT.md - - License: https://github.com/SAP/hybris-commerce-eclipse-plugin/blob/master/LICENSE + - Contributing: https://github.com/mikolayek/hybris-commerce-eclipse-plugin/blob/master/CONTRIBUTING.md + - Code of conduct: https://github.com/mikolayek/hybris-commerce-eclipse-plugin/blob/master/CODE_OF_CONDUCT.md + - License: https://github.com/mikolayek/hybris-commerce-eclipse-plugin/blob/master/LICENSE From 135ef17832495d2d324551d14c4ad20ea0fab625 Mon Sep 17 00:00:00 2001 From: Pawel Wolanski Date: Fri, 27 Nov 2026 10:31:44 +0100 Subject: [PATCH 11/25] Create jekyll-gh-pages.yml --- .github/workflows/jekyll-gh-pages.yml | 64 +++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 .github/workflows/jekyll-gh-pages.yml diff --git a/.github/workflows/jekyll-gh-pages.yml b/.github/workflows/jekyll-gh-pages.yml new file mode 100644 index 00000000..f1c738d5 --- /dev/null +++ b/.github/workflows/jekyll-gh-pages.yml @@ -0,0 +1,64 @@ +# Sample workflow for building and deploying a Jekyll site to GitHub Pages +name: Deploy Jekyll with GitHub Pages dependencies preinstalled + +on: + # Runs on pushes targeting the default branch + push: + branches: + - master + - release/* + + # Allows you to run this workflow manually from the Actions tab + workflow_dispatch: + +# Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages +permissions: + contents: read + pages: write + id-token: write + +# Allow only one concurrent deployment, skipping runs queued between the run in-progress and latest queued. +# However, do NOT cancel in-progress runs as we want to allow these production deployments to complete. +concurrency: + group: "pages" + cancel-in-progress: false + +jobs: + # Build job + build: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + - name: Setup Node + uses: actions/setup-node@v4 + with: + node-version: '20.x' + - name: Setup Pages + uses: actions/configure-pages@v5 + - name: Build with Jekyll + uses: actions/jekyll-build-pages@v1 + with: + source: ./ + destination: ./_site + - name: Upload artifact + uses: actions/upload-pages-artifact@v3 + + # Deployment job + deploy: + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + runs-on: ubuntu-latest + needs: build + steps: + - name: Install Dependencies + run: npm install + - name: Upload a Build Artifact + uses: actions/upload-artifact@v7.0.2 + with: + name: hybris-commerce-eclipse-plugin + path: /updatesite/** + - name: Deploy to GitHub Pages + id: deployment + uses: actions/deploy-pages@v5 From 176c1cfacd9906a200b5c6dd79c4e91e2c9d2b5d Mon Sep 17 00:00:00 2001 From: Pawel Wolanski Date: Fri, 27 Nov 2026 11:02:08 +0100 Subject: [PATCH 12/25] feat: docs jekyll Signed-off-by: Pawel Wolanski --- .github/workflows/jekyll-gh-pages.yml | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/.github/workflows/jekyll-gh-pages.yml b/.github/workflows/jekyll-gh-pages.yml index f1c738d5..88a02cb4 100644 --- a/.github/workflows/jekyll-gh-pages.yml +++ b/.github/workflows/jekyll-gh-pages.yml @@ -4,7 +4,7 @@ name: Deploy Jekyll with GitHub Pages dependencies preinstalled on: # Runs on pushes targeting the default branch push: - branches: + branches: - master - release/* @@ -31,16 +31,13 @@ jobs: - name: Checkout uses: actions/checkout@v4 - name: Setup Node - uses: actions/setup-node@v4 + uses: actions/setup-node@v7 with: - node-version: '20.x' + node-version: '24' - name: Setup Pages uses: actions/configure-pages@v5 - - name: Build with Jekyll + - name: Build uses: actions/jekyll-build-pages@v1 - with: - source: ./ - destination: ./_site - name: Upload artifact uses: actions/upload-pages-artifact@v3 From 8142111c2338ebb01e9072f85da6f4ad5301232d Mon Sep 17 00:00:00 2001 From: Pawel Wolanski Date: Fri, 27 Nov 2026 11:05:31 +0100 Subject: [PATCH 13/25] docs: remove unused npm install Signed-off-by: Pawel Wolanski --- .github/workflows/jekyll-gh-pages.yml | 6 ------ 1 file changed, 6 deletions(-) diff --git a/.github/workflows/jekyll-gh-pages.yml b/.github/workflows/jekyll-gh-pages.yml index 88a02cb4..6be25800 100644 --- a/.github/workflows/jekyll-gh-pages.yml +++ b/.github/workflows/jekyll-gh-pages.yml @@ -30,10 +30,6 @@ jobs: steps: - name: Checkout uses: actions/checkout@v4 - - name: Setup Node - uses: actions/setup-node@v7 - with: - node-version: '24' - name: Setup Pages uses: actions/configure-pages@v5 - name: Build @@ -49,8 +45,6 @@ jobs: runs-on: ubuntu-latest needs: build steps: - - name: Install Dependencies - run: npm install - name: Upload a Build Artifact uses: actions/upload-artifact@v7.0.2 with: From 211cb407d09749256367b1d7aa1e3fdc04ed068c Mon Sep 17 00:00:00 2001 From: Pawel Wolanski Date: Fri, 27 Nov 2026 11:08:22 +0100 Subject: [PATCH 14/25] chore: update gh action to node24 Signed-off-by: Pawel Wolanski --- .github/workflows/ci.yml | 2 +- .github/workflows/codeql.yml | 2 +- .github/workflows/dependency-review.yml | 2 +- .github/workflows/maven.yml | 4 ++-- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4392a643..00f166f0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -24,7 +24,7 @@ jobs: key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }} restore-keys: ${{ runner.os }}-m2 - name: Set up Maven - uses: stCarolas/setup-maven@v5 + uses: stCarolas/setup-maven@v5.1 with: maven-version: 3.9.15 - name: Build with Maven diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index 2031be8a..f16ca0ef 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -52,7 +52,7 @@ jobs: uses: actions/checkout@v7 - name: Set up Maven - uses: stCarolas/setup-maven@v5 + uses: stCarolas/setup-maven@v5.1 with: maven-version: 3.9.15 diff --git a/.github/workflows/dependency-review.yml b/.github/workflows/dependency-review.yml index dc8d2b46..4ad54d21 100644 --- a/.github/workflows/dependency-review.yml +++ b/.github/workflows/dependency-review.yml @@ -28,7 +28,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Set up Maven - uses: stCarolas/setup-maven@v5 + uses: stCarolas/setup-maven@v5.1 with: maven-version: 3.9.15 - name: 'Checkout repository' diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml index c91372fc..063e9fca 100644 --- a/.github/workflows/maven.yml +++ b/.github/workflows/maven.yml @@ -20,14 +20,14 @@ jobs: artifact-metadata: write contents: write pull-requests: write - + runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 - name: Set up Maven - uses: stCarolas/setup-maven@v5 + uses: stCarolas/setup-maven@v5.1 with: maven-version: 3.9.15 From 58601836b18d156a3bd750f9ed0f4a46f79325df Mon Sep 17 00:00:00 2001 From: Pawel Wolanski Date: Fri, 27 Nov 2026 11:23:51 +0100 Subject: [PATCH 15/25] update jekyll docs --- .github/workflows/docs.yml | 113 -------------------------- .github/workflows/jekyll-gh-pages.yml | 17 ++-- REUSE.toml | 2 +- _config.yml | 67 +++++++++++++++ mkdocs.yml | 80 ------------------ 5 files changed, 76 insertions(+), 203 deletions(-) delete mode 100644 .github/workflows/docs.yml create mode 100644 _config.yml delete mode 100644 mkdocs.yml diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml deleted file mode 100644 index af22e6d2..00000000 --- a/.github/workflows/docs.yml +++ /dev/null @@ -1,113 +0,0 @@ -name: Documentation and Eclipse update site - -on: - push: - branches: [master] - paths: - - 'README.md' - - 'docs/**' - - 'tools/docs/**' - - 'updatesite/**' - - 'mkdocs.yml' - - '.github/workflows/docs.yml' - pull_request: - paths: - - 'README.md' - - 'docs/**' - - 'tools/docs/**' - - 'updatesite/**' - - 'mkdocs.yml' - - '.github/workflows/docs.yml' - release: - types: [published] - workflow_dispatch: - inputs: - release_tag: - description: 'Optional vX.Y.Z tag to archive; blank updates Development only' - required: false - default: '' - type: string - -permissions: - contents: read - -concurrency: - group: docs-${{ github.workflow }}-${{ github.event_name == 'pull_request' && format('pr-{0}', github.event.pull_request.number) || 'publish' }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} - -jobs: - build: - runs-on: ubuntu-latest - permissions: - contents: read - pages: read - steps: - - uses: actions/checkout@v7 - with: - persist-credentials: false - fetch-depth: 0 - ref: ${{ github.event_name == 'release' && 'master' || github.ref }} - - uses: actions/setup-python@v7 - with: - python-version: '3.13' - cache: pip - cache-dependency-path: tools/docs/requirements.txt - - name: Install documentation dependencies - run: python -m pip install -r tools/docs/requirements.txt - - name: Test homepage and published resources - run: python -m unittest discover -s tools/docs -p 'test_*.py' - - name: Build documentation and validate Eclipse update site - run: python -m mkdocs build --strict - - name: Assemble versioned documentation and canonical Eclipse update site - env: - RELEASE_TAG: ${{ github.event.release.tag_name || inputs.release_tag || '' }} - GIT_AUTHOR_NAME: github-actions[bot] - GIT_AUTHOR_EMAIL: 41898282+github-actions[bot]@users.noreply.github.com - GIT_COMMITTER_NAME: github-actions[bot] - GIT_COMMITTER_EMAIL: 41898282+github-actions[bot]@users.noreply.github.com - run: python tools/docs/versioned_site.py --release-tag "$RELEASE_TAG" --export-history - - name: Transfer generated documentation history to deployment job - if: (github.ref == 'refs/heads/master' && github.event_name != 'pull_request') || github.event_name == 'release' - uses: actions/upload-artifact@v4 - with: - name: docs-history - path: docs-history.bundle - if-no-files-found: error - retention-days: 1 - - name: Configure Pages - if: (github.ref == 'refs/heads/master' && github.event_name != 'pull_request') || github.event_name == 'release' - uses: actions/configure-pages@v6 - - name: Upload Pages artifact - if: (github.ref == 'refs/heads/master' && github.event_name != 'pull_request') || github.event_name == 'release' - uses: actions/upload-pages-artifact@v5 - with: - path: site - - deploy: - if: (github.ref == 'refs/heads/master' && github.event_name != 'pull_request') || github.event_name == 'release' - needs: build - runs-on: ubuntu-latest - permissions: - contents: write - pages: write - id-token: write - environment: - name: github-pages - url: ${{ steps.deployment.outputs.page_url }} - steps: - - uses: actions/checkout@v7 - with: - ref: master - fetch-depth: 0 - persist-credentials: true - - uses: actions/download-artifact@v4 - with: - name: docs-history - path: ${{ runner.temp }}/docs-history - - name: Persist generated version archives without changing source branches - run: | - git fetch "$RUNNER_TEMP/docs-history/docs-history.bundle" docs-versions:refs/heads/docs-versions - git push origin refs/heads/docs-versions:refs/heads/docs-versions - - name: Deploy GitHub Pages - id: deployment - uses: actions/deploy-pages@v5 diff --git a/.github/workflows/jekyll-gh-pages.yml b/.github/workflows/jekyll-gh-pages.yml index 6be25800..1d6641ff 100644 --- a/.github/workflows/jekyll-gh-pages.yml +++ b/.github/workflows/jekyll-gh-pages.yml @@ -1,12 +1,12 @@ -# Sample workflow for building and deploying a Jekyll site to GitHub Pages +# Workflow for building and deploying the Jekyll site and Eclipse p2 update site to GitHub Pages name: Deploy Jekyll with GitHub Pages dependencies preinstalled on: - # Runs on pushes targeting the default branch + # Runs on pushes targeting the default branch or release branches push: branches: - - master - - release/* + - master + - release/* # Allows you to run this workflow manually from the Actions tab workflow_dispatch: @@ -34,6 +34,10 @@ jobs: uses: actions/configure-pages@v5 - name: Build uses: actions/jekyll-build-pages@v1 + - name: Copy Eclipse p2 repository as-is + run: | + rm -rf _site/updatesite + cp -rL updatesite _site/updatesite - name: Upload artifact uses: actions/upload-pages-artifact@v3 @@ -45,11 +49,6 @@ jobs: runs-on: ubuntu-latest needs: build steps: - - name: Upload a Build Artifact - uses: actions/upload-artifact@v7.0.2 - with: - name: hybris-commerce-eclipse-plugin - path: /updatesite/** - name: Deploy to GitHub Pages id: deployment uses: actions/deploy-pages@v5 diff --git a/REUSE.toml b/REUSE.toml index d5619216..11b79568 100644 --- a/REUSE.toml +++ b/REUSE.toml @@ -119,7 +119,7 @@ SPDX-FileCopyrightText = "2006 SAP SE or an SAP affiliate company and *Eclipse P SPDX-License-Identifier = "Apache-2.0" [[annotations]] -path = ["docs/**", ".github/**", "com.hybris.hyeclipse.site/**", ".gitignore", ".project", ".settings/**", ".travis", "CHANGELOG.md", "CODE_OF_CONDUCT.md", "README.md", "docs.code-workspace", "pom.xml", "CONTRIBUTING.md", "CONTRIBUTING_USING_GENAI.md", "REUSE.toml", ".travis.yml", "mkdocs.yml"] +path = ["docs/**", ".github/**", "com.hybris.hyeclipse.site/**", ".gitignore", ".project", ".settings/**", ".travis", "CHANGELOG.md", "CODE_OF_CONDUCT.md", "README.md", "docs.code-workspace", "pom.xml", "CONTRIBUTING.md", "CONTRIBUTING_USING_GENAI.md", "REUSE.toml", ".travis.yml", "_config.yml"] precedence = "aggregate" SPDX-FileCopyrightText = "2006 SAP SE or an SAP affiliate company and *Eclipse Plugin for SAP Commerce* contributors" SPDX-License-Identifier = "Apache-2.0" diff --git a/_config.yml b/_config.yml new file mode 100644 index 00000000..7b224831 --- /dev/null +++ b/_config.yml @@ -0,0 +1,67 @@ +title: Eclipse Plugin for SAP Commerce +description: User and developer documentation for the SAP Commerce Eclipse plugin. +url: "https://mikolayek.github.io" +baseurl: "/hybris-commerce-eclipse-plugin" + +theme: jekyll-theme-primer + +plugins: + - jekyll-optional-front-matter + - jekyll-readme-index + - jekyll-relative-links + - jekyll-titles-from-headings + +relative_links: + enabled: true + collections: true + +include: + - updatesite + +keep_files: + - updatesite + +exclude: + - AGENTS.md + - CLAUDE.md + - Makefile + - REUSE.toml + - docs.code-workspace + - mvnw + - mvnw.cmd + - pom.xml + - LICENSES/ + - site/ + - tools/ + - docs/docker-compose.yml + - docs/start-sonar.sh + - docs/dev/eclipse-code-style.xml + - .claude/ + - .github/ + - .metals/ + - .mvn/ + - .project + - .settings/ + - .venv-docs/ + - .vscode/ + - com.hybris.hyeclipse.commons/ + - com.hybris.hyeclipse.emf.beans/ + - com.hybris.hyeclipse.emf.beans.edit/ + - com.hybris.hyeclipse.emf.beans.editor/ + - com.hybris.hyeclipse.extgen/ + - com.hybris.hyeclipse.feature/ + - com.hybris.hyeclipse.hac/ + - com.hybris.hyeclipse.impex/ + - com.hybris.hyeclipse.impex.ls/ + - com.hybris.hyeclipse.impex.tests/ + - com.hybris.hyeclipse.impexed/ + - com.hybris.hyeclipse.importer/ + - com.hybris.hyeclipse.junit/ + - com.hybris.hyeclipse.junit.tests/ + - com.hybris.hyeclipse.platform/ + - com.hybris.hyeclipse.property.configuration/ + - com.hybris.hyeclipse.site/ + - com.hybris.hyeclipse.tests/ + - com.hybris.hyeclipse.tsv/ + - com.hybris.hyeclipse.tsv.extended/ + - com.hybris.hyeclipse.ytypesystem/ diff --git a/mkdocs.yml b/mkdocs.yml deleted file mode 100644 index 774b11da..00000000 --- a/mkdocs.yml +++ /dev/null @@ -1,80 +0,0 @@ -site_name: Eclipse Plugin for SAP Commerce -site_description: User and developer documentation for the SAP Commerce Eclipse plugin. -site_url: https://mikolayek.github.io/hybris-commerce-eclipse-plugin/ -repo_url: https://github.com/mikolayek/hybris-commerce-eclipse-plugin -repo_name: mikolayek/hybris-commerce-eclipse-plugin -edit_uri: edit/master/docs/ -docs_dir: docs -site_dir: site -remote_branch: docs-versions - -theme: - name: material - font: false - features: - - navigation.sections - - navigation.top - - content.action.edit - - content.code.copy - - search.highlight - -plugins: - - search - - mike: - alias_type: redirect - -extra: - version: - provider: mike - -hooks: - - tools/docs/hooks.py - -watch: - - README.md - - tools/docs - - updatesite - -exclude_docs: | - docker-compose.yml - start-sonar.sh - dev/eclipse-code-style.xml - internal/*.* - -validation: - nav: - omitted_files: warn - not_found: warn - links: - not_found: warn - anchors: warn - unrecognized_links: warn - -markdown_extensions: - - admonition - - toc: - permalink: true - - pymdownx.highlight - - pymdownx.superfences - -nav: - - Home: index.md - - User guide: - - Installation and update site: installation.md - - Project importer: importer/importer.md - - Beans generation: beangen/beangen.md - - JDK selection: import-jdk.md - - Troubleshooting: - - Knowledge database: kb/info.md - - Developer guide: - - Development and releases: dev/development.md - - Documentation and plugin versioning: dev/versioning.md - - ImpEx: - - Language behavior: dev/impex/impex-docs.md - - Editor migration plan: dev/impex/editor-replacement-plan.md - - Regression verification: dev/import-and-junit-verification.md - - Project information: - - Deprecations: deprecation/deprecation.md - - Contributing: https://github.com/mikolayek/hybris-commerce-eclipse-plugin/blob/master/CONTRIBUTING.md - - Code of conduct: https://github.com/mikolayek/hybris-commerce-eclipse-plugin/blob/master/CODE_OF_CONDUCT.md - - License: https://github.com/mikolayek/hybris-commerce-eclipse-plugin/blob/master/LICENSE From c2470cc196edb7ce1431e2fb11d240dabf518ce2 Mon Sep 17 00:00:00 2001 From: Pawel Wolanski Date: Fri, 27 Nov 2026 11:26:01 +0100 Subject: [PATCH 16/25] removing file modification as all are there --- .github/workflows/jekyll-gh-pages.yml | 4 ---- 1 file changed, 4 deletions(-) diff --git a/.github/workflows/jekyll-gh-pages.yml b/.github/workflows/jekyll-gh-pages.yml index 1d6641ff..24abdfdb 100644 --- a/.github/workflows/jekyll-gh-pages.yml +++ b/.github/workflows/jekyll-gh-pages.yml @@ -34,10 +34,6 @@ jobs: uses: actions/configure-pages@v5 - name: Build uses: actions/jekyll-build-pages@v1 - - name: Copy Eclipse p2 repository as-is - run: | - rm -rf _site/updatesite - cp -rL updatesite _site/updatesite - name: Upload artifact uses: actions/upload-pages-artifact@v3 From d0183ee918b8d8257eec32c422efa93147cb009c Mon Sep 17 00:00:00 2001 From: Pawel Wolanski Date: Fri, 27 Nov 2026 11:36:48 +0100 Subject: [PATCH 17/25] disable jekyll for now Signed-off-by: Pawel Wolanski --- .nojekyll | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 .nojekyll diff --git a/.nojekyll b/.nojekyll new file mode 100644 index 00000000..e69de29b From 469d0217e00132b81d61285e38799ac0b4ead2fb Mon Sep 17 00:00:00 2001 From: Pawel Wolanski Date: Fri, 27 Nov 2026 11:39:49 +0100 Subject: [PATCH 18/25] docs: remove jekyll Signed-off-by: Pawel Wolanski --- _config.yml | 67 ----------------------------------------------------- 1 file changed, 67 deletions(-) delete mode 100644 _config.yml diff --git a/_config.yml b/_config.yml deleted file mode 100644 index 7b224831..00000000 --- a/_config.yml +++ /dev/null @@ -1,67 +0,0 @@ -title: Eclipse Plugin for SAP Commerce -description: User and developer documentation for the SAP Commerce Eclipse plugin. -url: "https://mikolayek.github.io" -baseurl: "/hybris-commerce-eclipse-plugin" - -theme: jekyll-theme-primer - -plugins: - - jekyll-optional-front-matter - - jekyll-readme-index - - jekyll-relative-links - - jekyll-titles-from-headings - -relative_links: - enabled: true - collections: true - -include: - - updatesite - -keep_files: - - updatesite - -exclude: - - AGENTS.md - - CLAUDE.md - - Makefile - - REUSE.toml - - docs.code-workspace - - mvnw - - mvnw.cmd - - pom.xml - - LICENSES/ - - site/ - - tools/ - - docs/docker-compose.yml - - docs/start-sonar.sh - - docs/dev/eclipse-code-style.xml - - .claude/ - - .github/ - - .metals/ - - .mvn/ - - .project - - .settings/ - - .venv-docs/ - - .vscode/ - - com.hybris.hyeclipse.commons/ - - com.hybris.hyeclipse.emf.beans/ - - com.hybris.hyeclipse.emf.beans.edit/ - - com.hybris.hyeclipse.emf.beans.editor/ - - com.hybris.hyeclipse.extgen/ - - com.hybris.hyeclipse.feature/ - - com.hybris.hyeclipse.hac/ - - com.hybris.hyeclipse.impex/ - - com.hybris.hyeclipse.impex.ls/ - - com.hybris.hyeclipse.impex.tests/ - - com.hybris.hyeclipse.impexed/ - - com.hybris.hyeclipse.importer/ - - com.hybris.hyeclipse.junit/ - - com.hybris.hyeclipse.junit.tests/ - - com.hybris.hyeclipse.platform/ - - com.hybris.hyeclipse.property.configuration/ - - com.hybris.hyeclipse.site/ - - com.hybris.hyeclipse.tests/ - - com.hybris.hyeclipse.tsv/ - - com.hybris.hyeclipse.tsv.extended/ - - com.hybris.hyeclipse.ytypesystem/ From 051bcf92591d26dadeb7712af521a5c8c9702bb6 Mon Sep 17 00:00:00 2001 From: Pawel Wolanski Date: Fri, 27 Nov 2026 11:46:06 +0100 Subject: [PATCH 19/25] Create static.yml --- .github/workflows/static.yml | 43 ++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 .github/workflows/static.yml diff --git a/.github/workflows/static.yml b/.github/workflows/static.yml new file mode 100644 index 00000000..5b3c4e70 --- /dev/null +++ b/.github/workflows/static.yml @@ -0,0 +1,43 @@ +# Simple workflow for deploying static content to GitHub Pages +name: Deploy static content to Pages + +on: + # Runs on pushes targeting the default branch + push: + branches: ["master"] + + # Allows you to run this workflow manually from the Actions tab + workflow_dispatch: + +# Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages +permissions: + contents: read + pages: write + id-token: write + +# Allow only one concurrent deployment, skipping runs queued between the run in-progress and latest queued. +# However, do NOT cancel in-progress runs as we want to allow these production deployments to complete. +concurrency: + group: "pages" + cancel-in-progress: false + +jobs: + # Single deploy job since we're just deploying + deploy: + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + - name: Setup Pages + uses: actions/configure-pages@v5 + - name: Upload artifact + uses: actions/upload-pages-artifact@v3 + with: + # Upload entire repository + path: '/updatesite' + - name: Deploy to GitHub Pages + id: deployment + uses: actions/deploy-pages@v5 From 5108ae1bf6e7cd84aeb7db96939e0dbf3a057f70 Mon Sep 17 00:00:00 2001 From: Pawel Wolanski Date: Fri, 27 Nov 2026 11:47:47 +0100 Subject: [PATCH 20/25] Update static.yml --- .github/workflows/static.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/static.yml b/.github/workflows/static.yml index 5b3c4e70..40d714db 100644 --- a/.github/workflows/static.yml +++ b/.github/workflows/static.yml @@ -37,7 +37,7 @@ jobs: uses: actions/upload-pages-artifact@v3 with: # Upload entire repository - path: '/updatesite' + path: 'updatesite' - name: Deploy to GitHub Pages id: deployment uses: actions/deploy-pages@v5 From 0479ccffc28a28fd26bce0020acb0c9ac5146074 Mon Sep 17 00:00:00 2001 From: Pawel Wolanski Date: Fri, 27 Nov 2026 11:55:14 +0100 Subject: [PATCH 21/25] Update .nojekyll --- .nojekyll | 1 + 1 file changed, 1 insertion(+) diff --git a/.nojekyll b/.nojekyll index e69de29b..29280cc9 100644 --- a/.nojekyll +++ b/.nojekyll @@ -0,0 +1 @@ +nojekyll From 49c288b3612889abaa64dedcf44b12bc61fc66de Mon Sep 17 00:00:00 2001 From: Pawel Wolanski Date: Fri, 27 Nov 2026 12:13:25 +0100 Subject: [PATCH 22/25] refactor: streamline CI workflows, update gitignores, and add update site landing page --- .github/workflows/ci.yml | 16 +--- .github/workflows/codeql.yml | 5 -- .github/workflows/dependency-review.yml | 4 - .nojekyll | 1 + updatesite/index.html | 102 ++++++++++++++++++++++++ 5 files changed, 106 insertions(+), 22 deletions(-) create mode 100644 updatesite/index.html diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 00f166f0..fc67acb3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -16,18 +16,8 @@ jobs: with: distribution: "sapmachine" java-version: "21" - - - name: Cache Maven packages - uses: actions/cache@v6 - with: - path: ~/.m2 - key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }} - restore-keys: ${{ runner.os }}-m2 - - name: Set up Maven - uses: stCarolas/setup-maven@v5.1 - with: - maven-version: 3.9.15 - - name: Build with Maven - run: mvn --batch-mode --update-snapshots package + cache: maven + - name: MVN build + run: ./mvnw --batch-mode --update-snapshots package env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index f16ca0ef..10bc05bb 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -51,11 +51,6 @@ jobs: - name: Checkout repository uses: actions/checkout@v7 - - name: Set up Maven - uses: stCarolas/setup-maven@v5.1 - with: - maven-version: 3.9.15 - - name: Initialize CodeQL uses: github/codeql-action/init@v4 with: diff --git a/.github/workflows/dependency-review.yml b/.github/workflows/dependency-review.yml index 4ad54d21..953f0d8d 100644 --- a/.github/workflows/dependency-review.yml +++ b/.github/workflows/dependency-review.yml @@ -27,10 +27,6 @@ jobs: dependency-review: runs-on: ubuntu-latest steps: - - name: Set up Maven - uses: stCarolas/setup-maven@v5.1 - with: - maven-version: 3.9.15 - name: 'Checkout repository' uses: actions/checkout@v7 - name: 'Dependency Review' diff --git a/.nojekyll b/.nojekyll index e69de29b..7689f192 100644 --- a/.nojekyll +++ b/.nojekyll @@ -0,0 +1 @@ +nojekyll \ No newline at end of file diff --git a/updatesite/index.html b/updatesite/index.html new file mode 100644 index 00000000..aa7c47a2 --- /dev/null +++ b/updatesite/index.html @@ -0,0 +1,102 @@ + + + + + + Eclipse p2 Repository — hybris commerce eclipse plugin + + + +
+

Eclipse p2 Repository

+

+ This directory hosts the Eclipse p2 update site for the + hybris commerce eclipse plugin (Eclipse Plugin for SAP Commerce). +

+ +
+

Available Update Sites

+
    +
  • + latest/ — Latest published Eclipse p2 repository +
  • +
  • + neon/ — Eclipse p2 repository (neon) +
  • +
+
+ +
+

How to Install in Eclipse

+
    +
  1. Open Eclipse and select Help → Install New Software…
  2. +
  3. Click Add… and enter the latest/ or neon/ URL as the Location.
  4. +
  5. Select SAP Commerce, development tools for Eclipse and follow the installation wizard.
  6. +
+

+ Note: p2 repository directories contain Eclipse metadata (content.jar, + artifacts.jar, p2.index) for Eclipse’s installer rather than browsable HTML pages. +

+
+
+ + From 60cf05132a40a6d2dd7d8cb36412a54a6e9d6aee Mon Sep 17 00:00:00 2001 From: Pawel Wolanski Date: Fri, 27 Nov 2026 12:15:53 +0100 Subject: [PATCH 23/25] remove overlapping ci --- .github/workflows/maven.yml | 41 ------------------------------------- 1 file changed, 41 deletions(-) delete mode 100644 .github/workflows/maven.yml diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml deleted file mode 100644 index 063e9fca..00000000 --- a/.github/workflows/maven.yml +++ /dev/null @@ -1,41 +0,0 @@ -# This workflow will build a Java project with Maven, and cache/restore any dependencies to improve the workflow execution time -# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-java-with-maven - -# This workflow uses actions that are not certified by GitHub. -# They are provided by a third-party and are governed by -# separate terms of service, privacy policy, and support -# documentation. - -name: Java CI with Maven - -on: - push: - branches: [ "master" ] - pull_request: - branches: [ "master" ] - -jobs: - build: - permissions: - artifact-metadata: write - contents: write - pull-requests: write - - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v7 - - - name: Set up Maven - uses: stCarolas/setup-maven@v5.1 - with: - maven-version: 3.9.15 - - - name: Set up JDK 21 - uses: actions/setup-java@v6 - with: - java-version: '21' - distribution: 'temurin' - cache: maven - - name: Build with Maven - run: mvn -B package --file pom.xml From 32335aa46d3112b9c48f5cf6c9057a81e18c6585 Mon Sep 17 00:00:00 2001 From: Pawel Wolanski Date: Fri, 27 Nov 2026 12:26:04 +0100 Subject: [PATCH 24/25] chore: check with different path --- .github/workflows/static.yml | 2 +- updatesite/neon/index.html | 102 +++++++++++++++++++++++++++++++++++ 2 files changed, 103 insertions(+), 1 deletion(-) create mode 100644 updatesite/neon/index.html diff --git a/.github/workflows/static.yml b/.github/workflows/static.yml index 40d714db..e34c500c 100644 --- a/.github/workflows/static.yml +++ b/.github/workflows/static.yml @@ -37,7 +37,7 @@ jobs: uses: actions/upload-pages-artifact@v3 with: # Upload entire repository - path: 'updatesite' + path: '.' - name: Deploy to GitHub Pages id: deployment uses: actions/deploy-pages@v5 diff --git a/updatesite/neon/index.html b/updatesite/neon/index.html new file mode 100644 index 00000000..aa7c47a2 --- /dev/null +++ b/updatesite/neon/index.html @@ -0,0 +1,102 @@ + + + + + + Eclipse p2 Repository — hybris commerce eclipse plugin + + + +
+

Eclipse p2 Repository

+

+ This directory hosts the Eclipse p2 update site for the + hybris commerce eclipse plugin (Eclipse Plugin for SAP Commerce). +

+ +
+

Available Update Sites

+
    +
  • + latest/ — Latest published Eclipse p2 repository +
  • +
  • + neon/ — Eclipse p2 repository (neon) +
  • +
+
+ +
+

How to Install in Eclipse

+
    +
  1. Open Eclipse and select Help → Install New Software…
  2. +
  3. Click Add… and enter the latest/ or neon/ URL as the Location.
  4. +
  5. Select SAP Commerce, development tools for Eclipse and follow the installation wizard.
  6. +
+

+ Note: p2 repository directories contain Eclipse metadata (content.jar, + artifacts.jar, p2.index) for Eclipse’s installer rather than browsable HTML pages. +

+
+
+ + From b53eb85937de923a18196dbf2d7fc09a85d7fc9c Mon Sep 17 00:00:00 2001 From: Pawel Wolanski Date: Fri, 27 Nov 2026 13:41:00 +0100 Subject: [PATCH 25/25] chore: remove jekyll leftovers --- .github/workflows/jekyll-gh-pages.yml | 50 --------------------------- .nojekyll | 1 - 2 files changed, 51 deletions(-) delete mode 100644 .github/workflows/jekyll-gh-pages.yml delete mode 100644 .nojekyll diff --git a/.github/workflows/jekyll-gh-pages.yml b/.github/workflows/jekyll-gh-pages.yml deleted file mode 100644 index 24abdfdb..00000000 --- a/.github/workflows/jekyll-gh-pages.yml +++ /dev/null @@ -1,50 +0,0 @@ -# Workflow for building and deploying the Jekyll site and Eclipse p2 update site to GitHub Pages -name: Deploy Jekyll with GitHub Pages dependencies preinstalled - -on: - # Runs on pushes targeting the default branch or release branches - push: - branches: - - master - - release/* - - # Allows you to run this workflow manually from the Actions tab - workflow_dispatch: - -# Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages -permissions: - contents: read - pages: write - id-token: write - -# Allow only one concurrent deployment, skipping runs queued between the run in-progress and latest queued. -# However, do NOT cancel in-progress runs as we want to allow these production deployments to complete. -concurrency: - group: "pages" - cancel-in-progress: false - -jobs: - # Build job - build: - runs-on: ubuntu-latest - steps: - - name: Checkout - uses: actions/checkout@v4 - - name: Setup Pages - uses: actions/configure-pages@v5 - - name: Build - uses: actions/jekyll-build-pages@v1 - - name: Upload artifact - uses: actions/upload-pages-artifact@v3 - - # Deployment job - deploy: - environment: - name: github-pages - url: ${{ steps.deployment.outputs.page_url }} - runs-on: ubuntu-latest - needs: build - steps: - - name: Deploy to GitHub Pages - id: deployment - uses: actions/deploy-pages@v5 diff --git a/.nojekyll b/.nojekyll deleted file mode 100644 index 334496b1..00000000 --- a/.nojekyll +++ /dev/null @@ -1 +0,0 @@ -nojekyll