Browse Source

Merge branch 'lts-4.4' into feature/ai-websocket-channel

pull/16336/head
Igor Kulikov 2 months ago
parent
commit
c1fd06b0d1
  1. 26
      .github/workflows/check-license-headers.yml
  2. 5
      application/src/main/data/upgrade/lts/4.3.1.6/schema_update.sql
  3. 3
      application/src/main/java/org/thingsboard/server/service/install/EntityDatabaseSchemaService.java
  4. 5
      application/src/main/java/org/thingsboard/server/service/install/lts/V4_3_1_6Migration.java
  5. 5
      application/src/test/java/org/thingsboard/server/install/ThingsboardInstallServiceTest.java
  6. 5
      application/src/test/java/org/thingsboard/server/service/install/SqlEntityDatabaseSchemaServiceClusterIdTest.java
  7. 19
      check-license-headers.sh
  8. 3
      common/data/src/main/java/org/thingsboard/server/exception/DataValidationException.java
  9. 3
      common/transport/snmp/pom.xml
  10. 5
      dao/src/main/java/org/thingsboard/server/dao/subscription/TbClusterStore.java
  11. 5
      dao/src/test/java/org/thingsboard/server/dao/subscription/TbClusterStoreTest.java
  12. 56
      tools/src/main/python/license-headers/README.md
  13. 505
      tools/src/main/python/license-headers/check_license_headers.py
  14. 684
      tools/src/main/python/license-headers/curations.json
  15. 622
      tools/src/main/python/license-headers/test_check_license_headers.py
  16. 83
      ui-ngx/src/app/core/services/dashboard-utils.service.ts
  17. 23
      ui-ngx/src/app/core/services/resources.service.ts
  18. 25
      ui-ngx/src/app/modules/home/components/attribute/add-widget-to-dashboard-dialog.component.ts
  19. 46
      ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-page.component.html
  20. 87
      ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-page.component.ts
  21. 23
      ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-page.models.ts
  22. 8
      ui-ngx/src/app/modules/home/components/dashboard-page/layout/dashboard-layout.component.html
  23. 36
      ui-ngx/src/app/modules/home/components/dashboard-page/layout/dashboard-layout.component.ts
  24. 177
      ui-ngx/src/app/modules/home/components/dashboard-page/layout/manage-dashboard-layouts-dialog.component.html
  25. 86
      ui-ngx/src/app/modules/home/components/dashboard-page/layout/manage-dashboard-layouts-dialog.component.ts
  26. 8
      ui-ngx/src/app/modules/home/components/widget/config/basic/chart/comparison-keys-table.component.html
  27. 8
      ui-ngx/src/app/modules/home/components/widget/config/basic/html/html-container-basic-config.component.ts
  28. 11
      ui-ngx/src/app/modules/home/components/widget/lib/html/html-container-widget.component.ts
  29. 28
      ui-ngx/src/app/modules/home/components/widget/lib/html/html-container-widget.models.ts
  30. 6
      ui-ngx/src/app/modules/home/components/widget/lib/settings/common/html/html-container-settings.component.ts
  31. 5
      ui-ngx/src/app/modules/home/components/widget/lib/settings/html/html-container-widget-settings.component.ts
  32. 3
      ui-ngx/src/app/modules/home/components/widget/widget-container.component.ts
  33. 3
      ui-ngx/src/app/modules/home/pages/admin/resource/js-resource.component.ts
  34. 8
      ui-ngx/src/app/modules/home/pages/admin/trendz-settings.component.html
  35. 29
      ui-ngx/src/app/shared/models/dashboard.models.ts
  36. 25
      ui-ngx/src/app/shared/models/html-container.models.ts
  37. 6
      ui-ngx/src/assets/locale/locale.constant-en_US.json

26
.github/workflows/check-license-headers.yml

@ -11,19 +11,12 @@ on:
- master
- rc
- 'lts-[0-9]+.[0-9]+'
- 'license-lts-[0-9]+.[0-9]+'
pull_request:
branches:
- master
- rc
- 'lts-[0-9]+.[0-9]+'
- 'license-lts-[0-9]+.[0-9]+'
workflow_dispatch:
inputs:
ce-branch:
description: CE branch to compare against; defaults to the counterpart of the current branch
required: false
type: string
permissions:
contents: read
@ -53,27 +46,10 @@ jobs:
java-version: 21
cache: maven
- name: Resolve CE branch
id: ce
env:
PE_BRANCH: ${{ github.base_ref || github.ref_name }}
CE_BRANCH: ${{ inputs.ce-branch }}
run: |
if [[ -z "$CE_BRANCH" ]]; then
case "$PE_BRANCH" in
master|rc) CE_BRANCH="$PE_BRANCH" ;;
lts-*|license-lts-*) CE_BRANCH="${PE_BRANCH#license-}" ;;
*) echo "::error::No CE counterpart is defined for branch $PE_BRANCH"; exit 1 ;;
esac
fi
echo "branch=$CE_BRANCH" >> "$GITHUB_OUTPUT"
- name: Check license headers
env:
CE_BRANCH: ${{ steps.ce.outputs.branch }}
run: |
mkdir -p target/license-provenance
./check-license-headers.sh "${CE_BRANCH}" 2>&1 | tee target/license-provenance/console.log
./check-license-headers.sh 2>&1 | tee target/license-provenance/console.log
- name: Add findings to the job summary
if: failure() && hashFiles('target/license-provenance/console.log') != ''

5
application/src/main/data/upgrade/lts/4.3.1.6/schema_update.sql

@ -1,6 +1,7 @@
--
-- SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
-- SPDX-License-Identifier: BUSL-1.1
-- SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
-- SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
-- SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
--
-- A copy of the tb_cluster block in dao/src/main/resources/sql/schema-entities.sql, because the no-downtime patch

3
application/src/main/java/org/thingsboard/server/service/install/EntityDatabaseSchemaService.java

@ -1,6 +1,5 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
// SPDX-License-Identifier: Apache-2.0
package org.thingsboard.server.service.install;
public interface EntityDatabaseSchemaService extends DatabaseSchemaService {

5
application/src/main/java/org/thingsboard/server/service/install/lts/V4_3_1_6Migration.java

@ -1,5 +1,6 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
package org.thingsboard.server.service.install.lts;
import lombok.RequiredArgsConstructor;

5
application/src/test/java/org/thingsboard/server/install/ThingsboardInstallServiceTest.java

@ -1,5 +1,6 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
package org.thingsboard.server.install;
import org.junit.jupiter.api.BeforeEach;

5
application/src/test/java/org/thingsboard/server/service/install/SqlEntityDatabaseSchemaServiceClusterIdTest.java

@ -1,5 +1,6 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
package org.thingsboard.server.service.install;
import org.junit.jupiter.api.BeforeEach;

19
check-license-headers.sh

@ -8,21 +8,18 @@ set -euo pipefail
usage() {
echo "Checks SPDX license headers against CE provenance."
echo "usage: $0 <ce-ref> [--fix] [--ce-remote <url>] [--output target/...]"
echo " ce-ref CE branch, tag or commit matching this PE branch, e.g. lts-4.2;"
echo " fetched from the CE repository on every run"
echo "usage: $0 [--fix] [--ce-ref <ref>] [--ce-remote <url>] [--output target/...]"
echo " --fix restamp files whose expected header the check determined"
echo " --ce-remote CE repository to fetch from (default: https://github.com/thingsboard/thingsboard.git)"
echo " and remove redundant or orphaned curations"
echo " --ce-ref CE branch, tag or commit that this branch integrates, fetched on every run;"
echo " without it, CE is the history that does not contain the relicensing commit"
echo " --ce-remote CE repository to fetch --ce-ref from (default: https://github.com/thingsboard/thingsboard.git)"
}
if [[ $# -eq 0 || "$1" == "-h" || "$1" == "--help" || "$1" == -* ]]; then
if [[ $# -gt 0 && ( "$1" == "-h" || "$1" == "--help" ) ]]; then
usage
[[ $# -gt 0 && ( "$1" == "-h" || "$1" == "--help" ) ]] && exit 0
exit 2
exit 0
fi
ce_ref="$1"
shift
cd "$(git rev-parse --show-toplevel)"
exec python3 tools/src/main/python/license-headers/check_license_headers.py check --ce-ref "$ce_ref" "$@"
exec python3 tools/src/main/python/license-headers/check_license_headers.py check "$@"

3
common/data/src/main/java/org/thingsboard/server/exception/DataValidationException.java

@ -1,6 +1,5 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
// SPDX-License-Identifier: Apache-2.0
package org.thingsboard.server.exception;
public class DataValidationException extends RuntimeException {

3
common/transport/snmp/pom.xml

@ -1,7 +1,8 @@
<!--
SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
SPDX-License-Identifier: Apache-2.0
SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

5
dao/src/main/java/org/thingsboard/server/dao/subscription/TbClusterStore.java

@ -1,5 +1,6 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
package org.thingsboard.server.dao.subscription;
import lombok.RequiredArgsConstructor;

5
dao/src/test/java/org/thingsboard/server/dao/subscription/TbClusterStoreTest.java

@ -1,5 +1,6 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
package org.thingsboard.server.dao.subscription;
import org.junit.jupiter.api.Test;

56
tools/src/main/python/license-headers/README.md

@ -1,29 +1,52 @@
# License header provenance check
Verifies that every file carries the SPDX header its origin requires: `apache`
for unchanged CE files, `ce-modified` for CE files with PE changes, `pe-only`
for files that do not exist in CE. A `pom.xml` added in PE under a directory
that has no files in CE is `pe-only` even when it resembles a CE `pom.xml`:
module identity, dependencies and packaging define the PE artifact.
for unchanged CE files, `ce-modified` for CE files with changes, and the third
header of this repository, `busl`, for files that do not come from CE. The
third header is the only `templates/license-header-<kind>.txt` besides the
`ce-modified` one, and its `<kind>` names it in the output and in curations.
CE is the history of the ThingsBoard Community Edition under Apache-2.0. The
check compares against the latest CE commits merged into the current branch:
- By default, CE commits are the ones that do not have the relicensing commit
`31936b09d24` in their history, for example pre-4.4 master and the lts-4.3
commits merged into lts-4.4.
- With `--ce-ref`, CE commits are the history of the given CE branch, tag, or
commit, without the commits that have the relicensing commit in their
history. Use it when the history of the current branch does not come from CE
alone. The ref is fetched from `https://github.com/thingsboard/thingsboard.git`
on every run; pass `--ce-remote` to fetch from another URL or a local clone.
## Rules
A file whose path exists in CE is `apache` when its content without the
header equals a CE version of it, or a clean merge of its CE versions, and
`ce-modified` otherwise.
A file whose path does not exist in CE is `busl`, except when it needs a
decision: its content is at least 50% similar to a CE file, or CE history once
had this path. A `pom.xml` added under a directory that has no files in CE is
`busl` even when it resembles a CE `pom.xml`: module identity, dependencies and
packaging define the new artifact.
## Run
```sh
./check-license-headers.sh lts-4.2
./check-license-headers.sh
```
The argument is the CE branch, tag, or commit matching the current PE branch. It
is fetched from `https://github.com/thingsboard/thingsboard.git` on every run, so
the clone needs network access but no CE remote of its own. Pass `--ce-remote`
to fetch from another URL or a local CE clone instead.
The check needs the full Git history of the clone.
## Fix automatically
```sh
./check-license-headers.sh lts-4.2 --fix
./check-license-headers.sh --fix
```
Restamps every file whose expected header the check determined by itself.
Restamps every file whose expected header the check determined by itself and
removes curations that are redundant, because the check decides the same header
by itself, or that belong to files no longer in scope.
## Add a curation
@ -31,15 +54,18 @@ For files the check cannot decide ("Needs a decision"), record the decision in
`curations.json` next to this file:
1. Put the correct header on the file. A file that exists in CE, even renamed
or moved, is `ce-modified`; a file that does not exist in CE is `pe-only`.
or moved, is `ce-modified`; a file that does not exist in CE is `busl`.
2. Run `sha256sum path/to/File.java`.
3. Add an entry and rerun the check:
```json
{
"path": "path/to/File.java",
"contentHash": "sha256:<64 hex digits>",
"header": "pe-only",
"reason": "Which CE file this was compared against and why the header follows."
"header": "busl",
"reason": "Which CE file this was compared against and why the header follows.",
"contentHash": "sha256:<64 hex digits>"
}
```
A curation whose file changed since the review is stale and fails the check
until someone reviews the file again and updates `contentHash`.

505
tools/src/main/python/license-headers/check_license_headers.py

@ -24,11 +24,24 @@ import uuid
import xml.etree.ElementTree as ET
TEMPLATE_DIRECTORY = "tools/src/main/python/license-headers/templates"
def non_ce_header(directory):
kinds = sorted(path.name[len("license-header-"):-len(".txt")] for path in directory.glob("license-header-*.txt"))
kinds = [kind for kind in kinds if kind != "ce-modified"]
if len(kinds) != 1:
raise RuntimeError(f"Expected exactly one license-header-<kind>.txt besides the ce-modified one in {directory}")
return kinds[0]
NON_CE = non_ce_header(Path(__file__).resolve().parent / "templates")
TEMPLATES = {
"apache": "tools/src/main/python/license-headers/templates/license-header.txt",
"ce-modified": "tools/src/main/python/license-headers/templates/license-header-ce-modified.txt",
"pe-only": "tools/src/main/python/license-headers/templates/license-header-busl.txt",
"apache": f"{TEMPLATE_DIRECTORY}/license-header.txt",
"ce-modified": f"{TEMPLATE_DIRECTORY}/license-header-ce-modified.txt",
NON_CE: f"{TEMPLATE_DIRECTORY}/license-header-{NON_CE}.txt",
}
RELICENSING_COMMIT = "31936b09d24871e421f212502a8342f9d8aabb20"
CE_REMOTE = "https://github.com/thingsboard/thingsboard.git"
CURATIONS = "tools/src/main/python/license-headers/curations.json"
README = "tools/src/main/python/license-headers/README.md"
@ -152,16 +165,37 @@ def fetch(repo, remote, ref):
return resolve(repo, "FETCH_HEAD")
def unique_base(repo, left, right):
bases = git(repo, "merge-base", "--all", left, right).decode().splitlines()
if len(bases) != 1:
raise Failure(f"found {len(bases)} merge bases between PE HEAD and the CE ref, expected exactly one. "
"Check that the right CE branch was passed.")
return bases[0]
def independent(repo, commits):
return sorted(git(repo, "merge-base", "--independent", *commits).decode().split())
def contains(repo, ancestor, descendant):
return run(["git", "merge-base", "--is-ancestor", ancestor, descendant], repo, ok=(0, 1, 128)).returncode == 0
def first_parent_commits(repo, revision):
return git(repo, "rev-list", "--first-parent", revision).decode().splitlines()
def relicensed_ce_bases(repo, head):
if not contains(repo, RELICENSING_COMMIT, head):
raise Failure(f"the relicensing commit {RELICENSING_COMMIT[:11]} is not in the history of HEAD. "
"Pass --ce-ref with the CE branch that this branch integrates.")
records = git(repo, "rev-list", "--parents", "--ancestry-path", f"{RELICENSING_COMMIT}..{head}").decode().splitlines()
records.append(git(repo, "rev-list", "--parents", "-1", RELICENSING_COMMIT).decode().strip())
commits = {record.split()[0] for record in records}
parents = {parent for record in records for parent in record.split()[1:]}
return independent(repo, sorted(parents - commits))
def merged_ce_bases(repo, head, baseline):
bases = run(["git", "merge-base", "--all", head, baseline], repo, ok=(0, 1)).stdout.decode().split()
if not bases:
raise Failure("HEAD shares no history with the CE ref. Check that the right CE branch was passed.")
ce = [ce_base for base in bases
for ce_base in (relicensed_ce_bases(repo, base) if contains(repo, RELICENSING_COMMIT, base) else [base])]
return independent(repo, ce)
def merge_blobs(repo, ours, base, theirs):
result = run(["git", "merge-file", "-p", "--object-id", ours, base, theirs], repo, ok=range(0, 256))
return result.stdout if result.returncode == 0 else None
def tree(repo, revision):
@ -203,10 +237,6 @@ class Change:
new: str
status: str
@property
def deleted(self):
return self.status == "D"
def history(repo, revision, *options):
raw = git(repo, "log", "--first-parent", "--diff-merges=first-parent", "--root", "--raw", "--no-abbrev",
@ -239,21 +269,6 @@ def parse_history(raw):
raise Failure(f"Unexpected Git history token: {token[:80]!r}")
def integration_boundary(repo, anchor, head):
chain = first_parent_commits(repo, head)
low, high = 0, len(chain)
while low < high:
middle = (low + high) // 2
code = run(["git", "merge-base", "--is-ancestor", anchor, chain[middle]], repo, ok=(0, 1)).returncode
if code == 0:
low = middle + 1
else:
high = middle
if not low:
raise Failure("CE anchor is not in PE history")
return chain[low - 1]
def git_ignored(repo, paths):
if not paths:
return set()
@ -513,7 +528,7 @@ class Mycila:
(directory / name).write_bytes(self.templates[header])
def add(self, key, name, content):
group = "pe" if key[0] == "pe" else "ce"
group = "head" if key[0] == "head" else "ce"
path = self.root / "files" / group / str(len(self.paths)) / PurePosixPath(name).name
path.parent.mkdir(parents=True)
path.write_bytes(content)
@ -561,11 +576,11 @@ class Mycila:
def remove_headers(self, keys):
before = {key: self.contents[key] for key in keys}
with self.guarded(keys):
results = self.invoke("remove", "pe-only", keys, styles=(STRICT_XML,))
results = self.invoke("remove", NON_CE, keys, styles=(STRICT_XML,))
unchanged = [key for key, result in results.items()
if result == "NOOP" and PurePosixPath(self.paths[key]).suffix in BLOCK_COMMENT_SUFFIXES]
if unchanged:
self.invoke("remove", "pe-only", unchanged, styles=(STRICT_XML, STRICT_BLOCK))
self.invoke("remove", NON_CE, unchanged, styles=(STRICT_XML, STRICT_BLOCK))
removed = {}
for key in keys:
content, removed[key] = split_removed(before[key], self.contents[key])
@ -690,14 +705,14 @@ class Mycila:
selected = set(keys)
if selected == set(self.paths):
return ["files/**"]
if selected == {key for key in self.paths if key[0] == "pe"}:
return ["files/pe/**"]
if selected == {key for key in self.paths if key[0] == "head"}:
return ["files/head/**"]
return [str(PurePosixPath(self.paths[key]).parent) + "/*" for key in keys]
def normalized_copies(mycila, source_refs, names, nonempty):
sources = set(source_refs) & nonempty
destinations = {("pe", name) for name in names} & nonempty
destinations = {("head", name) for name in names} & nonempty
if not sources or not destinations:
return {}
git(mycila.root, "init", "--quiet")
@ -712,7 +727,7 @@ def normalized_copies(mycila, source_refs, names, nonempty):
for source, destination, similarity in parse_copies(raw):
source_key, destination_key = keys[source], keys[destination]
if source_key not in sources or destination_key not in destinations:
raise Failure("Normalized copy escaped the selected CE/PE inputs")
raise Failure("Normalized copy escaped the selected CE and HEAD inputs")
copies[destination_key[1]].append({"path": source_key[0], "blob": source_key[1],
"ref": source_refs[source_key], "similarity": similarity})
return dict(copies)
@ -742,160 +757,78 @@ class Evidence:
path: str
content_hash: str
current: str
curation: dict | None
inherited: bool
recreated: bool
ce_hash: str | None
pe_hash: str
candidates: list
historical: list
in_comparison: bool
pe_addition: bool = False
curation: dict | None = None
ce_versions: tuple = ()
identical: dict | None = None
copies: tuple = ()
deleted: dict | None = None
directory_in_ce: bool = True
ce_ref: str | None = None
ce_blob: str | None = None
@property
def strong(self):
return [c for c in self.historical if c["path"] == self.path or c.get("contentMatches")]
def ce_traces(self):
return bool(self.candidates or self.copies or self.in_comparison or self.strong)
def pe_module_descriptor(self):
def module_descriptor(self):
return (PurePosixPath(self.path).name == MODULE_DESCRIPTOR and not self.directory_in_ce
and not (self.candidates or self.in_comparison or self.strong))
and self.deleted is None and all(copy["similarity"] < 100 for copy in self.copies))
def decide(evidence):
row = {"path": evidence.path, "contentHash": evidence.content_hash, "currentHeader": evidence.current}
if evidence.curation is not None:
return row | curated_verdict(evidence)
if evidence.recreated:
return row | {"status": "unresolved", "expectedHeader": None,
"reason": "deleted and recreated at this path, origin unclear"}
if evidence.inherited and evidence.ce_hash is not None:
comparison = {"comparison": {"path": evidence.path, "ref": evidence.ce_ref, "blob": evidence.ce_blob}}
if evidence.pe_hash == evidence.ce_hash:
return row | verdict(evidence.current, "apache", "same path in CE, content identical") | comparison
return row | verdict(evidence.current, "ce-modified", "same path in CE, content differs") | comparison
if evidence.pe_addition and not evidence.ce_traces():
return row | verdict(evidence.current, "pe-only", "added in PE, no CE evidence")
if evidence.pe_addition and evidence.pe_module_descriptor():
return row | verdict(evidence.current, "pe-only", "build descriptor of a module that does not exist in CE")
return row | open_question(evidence)
inferred = infer(evidence)
curation = evidence.curation
if curation is None:
return row | inferred
if curation["contentHash"] != evidence.content_hash:
return row | {"status": "stale-curation", "expectedHeader": None,
"reason": "file changed since the curation, re-review and update contentHash"}
if inferred["expectedHeader"] == curation["header"]:
return row | inferred | {"redundantCuration": True}
return row | verdict(evidence.current, curation["header"], "curation: " + curation["reason"])
def infer(evidence):
if evidence.ce_versions:
versions = {"ceVersions": list(evidence.ce_versions)}
if evidence.identical is None:
return verdict(evidence.current, "ce-modified", "same path in CE, content differs") | versions
reason = ("same path in CE, content identical" if "blob" in evidence.identical
else "same path in CE, content identical to a clean merge of its CE versions")
return verdict(evidence.current, "apache", reason) | versions | {"identicalTo": evidence.identical}
if evidence.module_descriptor():
return verdict(evidence.current, NON_CE, "build descriptor of a module that does not exist in CE")
if evidence.copies:
suggested = "apache" if evidence.copies[0]["similarity"] == 100 else None
return unresolved("similar content exists in CE under another path", suggested,
copyCandidates=list(evidence.copies))
if evidence.deleted is not None:
return unresolved("CE history had this path", None, historicalCandidate=evidence.deleted)
return verdict(evidence.current, NON_CE, "not in CE, no CE evidence")
def verdict(current, expected, reason):
return {"status": "match" if current == expected else "mismatch", "expectedHeader": expected, "reason": reason}
def curated_verdict(evidence):
curation = evidence.curation
if curation["contentHash"] != evidence.content_hash:
return {"status": "stale-curation", "expectedHeader": None,
"reason": "file changed since the curation, re-review and update contentHash"}
return verdict(evidence.current, curation["header"], "curation: " + curation["reason"])
def open_question(evidence):
strong = evidence.strong
ranked = [
(evidence.candidates, "identical content exists in CE under another path", "apache"),
(evidence.copies, "similar content exists in CE under another path", None),
(strong, "CE history has this path or content", None),
(evidence.in_comparison, "present in CE, but not in the shared ancestry", None),
(True, "no CE evidence, but not proven to be added in PE", "pe-only"),
]
_, reason, suggested = next(item for item in ranked if item[0])
return {
"status": "unresolved",
"expectedHeader": None,
"suggestedHeader": suggested,
"reason": reason,
"candidates": evidence.candidates[:10],
"historicalCandidates": strong[:10],
"copyCandidates": list(evidence.copies),
"candidateCount": len(evidence.candidates),
"historicalCandidateCount": len(strong),
}
def unresolved(reason, suggested, **candidates):
return {"status": "unresolved", "expectedHeader": None, "suggestedHeader": suggested, "reason": reason} | candidates
@dataclass(frozen=True)
class Lineage:
head: str
baseline: str
anchor: str
boundary: str
ce_commits: frozenset
ce_changes: list
comparison: dict
shared: dict
pe_tree: dict
additions: dict
recreated: frozenset
bases: tuple
trees: dict
deleted: dict
@classmethod
def load(cls, repo, head, baseline):
def load(cls, repo, head, bases):
if git(repo, "rev-parse", "--is-shallow-repository").decode().strip() == "true":
raise Failure("this clone is shallow and the check needs full history. Run git fetch --unshallow.")
anchor = unique_base(repo, head, baseline)
ce_chain = first_parent_commits(repo, baseline)
ce_commits = frozenset(ce_chain)
if anchor not in ce_commits:
raise Failure("the shared ancestor is not on the CE ref's first-parent chain. "
"Pass the CE mainline branch that the PE branch integrates.")
boundary = integration_boundary(repo, anchor, head)
shared = tree(repo, anchor)
additions = {}
for change in history(repo, head, "--diff-filter=A"):
additions.setdefault(change.path, change.commit)
ce_changes = history(repo, baseline)
divergent = frozenset(ce_chain[:ce_chain.index(anchor)])
divergence = (history(repo, f"{boundary}..{head}")
+ [change for change in ce_changes if change.commit in divergent])
return cls(
head=head,
baseline=baseline,
anchor=anchor,
boundary=boundary,
ce_commits=ce_commits,
ce_changes=ce_changes,
comparison=tree(repo, baseline),
shared=shared,
pe_tree=tree(repo, head),
additions=additions,
recreated=frozenset(change.path for change in divergence
if change.status in {"A", "D"} and change.path in shared),
)
def unmatched(self, names):
return {name for name in names
if name not in self.shared or name not in self.comparison or name in self.recreated}
def pe_addition(self, name):
if name not in self.pe_tree:
return True
return name in self.additions and self.additions[name] not in self.ce_commits
def added_by(self, name):
if name not in self.pe_tree:
return self.additions.get(name, "working-tree addition")
return self.additions.get(name)
def historical_versions(ce_changes, unmatched):
basenames = {PurePosixPath(name).name for name in unmatched}
versions = {}
for change in ce_changes:
if change.path not in unmatched and PurePosixPath(change.path).name not in basenames:
continue
oid = change.old if change.deleted else change.new
if set(oid) == {"0"}:
continue
versions.setdefault((change.path, oid), change.commit + "^1" if change.deleted else change.commit)
return versions
deleted = {}
for base in bases:
for change in history(repo, base, "--diff-filter=D"):
deleted.setdefault(change.path, {"path": change.path, "ref": change.commit + "^1", "blob": change.old})
return cls(head=head, bases=tuple(bases), trees={base: tree(repo, base) for base in bases}, deleted=deleted)
def versions(self, name):
return [(base, files[name]) for base, files in self.trees.items() if name in files]
def comparable_ce_files(comparison, names):
@ -909,108 +842,114 @@ def comparable_ce_files(comparison, names):
class Comparison:
lineage: Lineage
contents: dict
unmatched: set
headers: dict
normalized: dict
nonempty: set
copies: dict
exact_index: dict
historic_index: dict
merges: dict
ce_directories: frozenset
def classify(self, name, curation):
key = ("pe", name)
lineage = self.lineage
unmatched = name in self.unmatched
historic = self.historical_candidates(name) if unmatched else []
evidence = Evidence(
key = ("head", name)
versions = self.lineage.versions(name)
identical = next(({"path": name, "ref": base, "blob": oid} for base, oid in versions
if self.normalized[(name, oid)] == self.normalized[key]), self.merges.get(name))
copies = sorted(self.copies.get(name, []), key=lambda copy: (-copy["similarity"], copy["path"]))
return decide(Evidence(
path=name,
content_hash=raw_hash(self.contents[name]),
current=self.headers[key],
curation=curation,
inherited=name in lineage.shared,
recreated=name in lineage.recreated,
ce_hash=self.normalized.get((name, lineage.comparison.get(name))),
pe_hash=self.normalized[key],
candidates=self.exact_index.get(self.normalized[key], []) if unmatched else [],
historical=historic,
in_comparison=name in lineage.comparison,
pe_addition=lineage.pe_addition(name),
copies=self.copies.get(name, []),
ce_versions=tuple({"path": name, "ref": base, "blob": oid} for base, oid in versions),
identical=identical,
copies=tuple(copies),
deleted=self.lineage.deleted.get(name),
directory_in_ce=str(PurePosixPath(name).parent) in self.ce_directories,
ce_ref=lineage.baseline,
ce_blob=lineage.comparison.get(name),
)
row = decide(evidence)
if unmatched:
row["peAddition"] = lineage.added_by(name)
row["basenameHintCount"] = len(historic) - len(evidence.strong)
return row
def historical_candidates(self, name):
key = ("pe", name)
candidates = []
for version in self.historic_index.get(PurePosixPath(name).name, []):
matches = (key in self.nonempty
and self.normalized[key] == self.normalized[(version["path"], version["blob"])])
candidates.append(version | {"contentMatches": matches})
candidates.sort(key=lambda candidate: (not candidate["contentMatches"], candidate["path"] != name))
return candidates
))
def compare(repo, plugin, lineage, contents):
names = list(contents)
unmatched = lineage.unmatched(names)
versions = historical_versions(lineage.ce_changes, unmatched)
counterparts = comparable_ce_files(lineage.comparison, names)
source_refs = versions | {key: lineage.baseline for key in counterparts.items()}
bytes_by_id = blobs(repo, [oid for _, oid in source_refs])
new_paths = {name for name in names if not lineage.versions(name)}
sources = {}
for base, files in lineage.trees.items():
for name in names:
if name in files:
sources.setdefault((name, files[name]), base)
for key in comparable_ce_files(files, new_paths).items():
sources.setdefault(key, base)
bytes_by_id = blobs(repo, [oid for _, oid in sources])
with tempfile.TemporaryDirectory(prefix="license-provenance-") as temporary:
mycila = Mycila(repo, Path(temporary), plugin)
for name, content in contents.items():
mycila.add(("pe", name), name, content)
for path, oid in sorted(source_refs):
mycila.add(("head", name), name, content)
for path, oid in sorted(sources):
mycila.add((path, oid), path, bytes_by_id[oid])
console.begin("Recognizing headers")
recognized = mycila.current_headers([("pe", name) for name in names])
recognized = mycila.current_headers([("head", name) for name in names])
console.end()
console.begin("Comparing against CE")
normalized = mycila.strip_headers()
headers = mycila.header_states(recognized)
nonempty = mycila.nonempty()
copies = normalized_copies(mycila, source_refs, unmatched, nonempty)
exact_index = defaultdict(list)
for path, oid in counterparts.items():
if (path, oid) in nonempty:
exact_index[normalized[(path, oid)]].append({"path": path, "ref": lineage.baseline, "blob": oid})
historic_index = defaultdict(list)
for (path, oid), ref in versions.items():
historic_index[PurePosixPath(path).name].append({"path": path, "ref": ref, "blob": oid})
copies = normalized_copies(mycila, sources, new_paths, mycila.nonempty())
merges = clean_merges(repo, plugin, lineage, names, normalized)
console.end(f"done ({len(normalized)} file versions)")
return Comparison(
lineage=lineage,
contents=contents,
unmatched=unmatched,
headers=headers,
normalized=normalized,
nonempty=nonempty,
copies=copies,
exact_index=dict(exact_index),
historic_index=dict(historic_index),
ce_directories=frozenset(str(parent) for path in lineage.comparison for parent in PurePosixPath(path).parents),
merges=merges,
ce_directories=frozenset(str(parent) for files in lineage.trees.values()
for path in files for parent in PurePosixPath(path).parents),
)
def clean_merges(repo, plugin, lineage, names, normalized):
merged = {}
for index, left in enumerate(lineage.bases):
for right in lineage.bases[index + 1:]:
ancestors = git(repo, "merge-base", "--all", left, right).decode().split()
if len(ancestors) != 1:
continue
ancestry = tree(repo, ancestors[0])
for name in names:
ours, theirs = lineage.trees[left].get(name), lineage.trees[right].get(name)
if ours is None or theirs is None or ours == theirs or name not in ancestry:
continue
if normalized[("head", name)] in {normalized[(name, ours)], normalized[(name, theirs)]}:
continue
content = merge_blobs(repo, ours, ancestry[name], theirs)
if content is not None:
merged[(name, left, right)] = (content, {"path": name, "merge": [left, right],
"base": ancestors[0]})
if not merged:
return {}
with tempfile.TemporaryDirectory(prefix="license-provenance-") as temporary:
mycila = Mycila(repo, Path(temporary), plugin)
for key, (content, _) in merged.items():
mycila.add(key, key[0], content)
hashes = mycila.strip_headers()
result = {}
for key, (_, description) in merged.items():
if hashes[key] == normalized[("head", key[0])]:
result.setdefault(key[0], description)
return result
def current_branch(repo):
branch = git(repo, "rev-parse", "--abbrev-ref", "HEAD").decode().strip()
return "" if branch == "HEAD" else branch
def print_banner(repo, head, ce_remote, ce_ref, baseline):
def print_banner(repo, head, ce):
console.line("License header provenance check")
console.line(f" PE head {head[:11]} {current_branch(repo)}".rstrip())
console.line(f" CE remote {ce_remote}")
console.line(f" CE ref {ce_ref}" + (f" → {baseline[:11]}" if baseline != ce_ref else ""))
console.line(f" HEAD {head[:11]} {current_branch(repo)}".rstrip())
if "ref" in ce:
console.line(f" CE remote {ce['remote']}")
console.line(f" CE ref {ce['ref']}" + (f" → {ce['commit'][:11]}" if ce["commit"] != ce["ref"] else ""))
else:
console.line(f" CE commits without the relicensing commit {ce['relicensingCommit'][:11]} in their history")
console.line()
@ -1039,16 +978,15 @@ def describe_mismatch(row):
def describe_unresolved(row, ref_names):
hint = f" (hint: {row['suggestedHeader']})" if row.get("suggestedHeader") else ""
details = [f"has {header_name(row['currentHeader'])}, no expected header yet{hint}"]
evidence = ([("exact CE match", candidate) for candidate in row.get("candidates", [])]
+ [(f"similar CE file ({candidate['similarity']}%)", candidate)
for candidate in row.get("copyCandidates", [])]
+ [("CE history", candidate) for candidate in row.get("historicalCandidates", [])])
evidence = [(f"similar CE file ({candidate['similarity']}%)", candidate)
for candidate in row.get("copyCandidates", [])]
if "historicalCandidate" in row:
evidence.append(("CE history", row["historicalCandidate"]))
if not evidence:
return details + [row["reason"]]
label, candidate = evidence[0]
details.append(f"{label}: {candidate['path']} at {ref_name(candidate['ref'], ref_names)}")
others = (row.get("candidateCount", 0) + len(row.get("copyCandidates", []))
+ row.get("historicalCandidateCount", 0) - 1)
others = len(evidence) - 1
if others > 0:
details.append(f"another {others} candidate{'s' if others != 1 else ''} in the report")
return details
@ -1058,8 +996,12 @@ def describe_stale(row):
return [row["reason"]]
def print_group(title, rows, describe, hint):
console.line(f"{title} ({len(rows)})", "red")
def describe_redundant(row):
return [f"curated {row['expectedHeader']}, the check decides {row['expectedHeader']} by itself"]
def print_group(title, rows, describe, hint, style="red"):
console.line(f"{title} ({len(rows)})", style)
for row in rows:
console.line(f" {row['path']}")
for detail in describe(row):
@ -1084,6 +1026,16 @@ def print_restamped(rows):
console.line()
def print_removed_curations(removed):
if not removed:
return
console.line(f"Removed curations ({len(removed)})", "green")
for entry in removed:
console.line(f" {entry['path']}")
console.line(f" {entry['reason']}")
console.line()
def print_findings(rows, curation_issues, ref_names):
mismatches = [row for row in rows if row["status"] == "mismatch"]
unresolved = [row for row in rows if row["status"] == "unresolved"]
@ -1096,7 +1048,14 @@ def print_findings(rows, curation_issues, ref_names):
print_group("Needs a decision", unresolved, lambda row: describe_unresolved(row, ref_names),
f"Decide the origin and add a curation, see {README}")
if stale:
print_group("Stale curations", stale, describe_stale, f"Remove or update the entry in {CURATIONS}")
hint = (f"Review the file and update the entry in {CURATIONS}; --fix removes entries of files no longer in scope"
if any(row["status"] == "stale-curation" and "contentHash" in row for row in stale)
else "Rerun with --fix to remove them")
print_group("Stale curations", stale, describe_stale, hint)
redundant = [row for row in rows if row.get("redundantCuration")]
if redundant:
print_group("Redundant curations", redundant, describe_redundant,
f"Rerun with --fix to remove them from {CURATIONS}", style=None)
def print_summary(rows, curation_issues, report):
@ -1145,8 +1104,8 @@ def restamp(repo, plugin, rows, contents):
templates = {header: template_lines(content) for header, content in mycila.templates.items()}
for name, header in current.items():
if header not in TEMPLATES:
expected[("pe", name)] = wanted[name]
mycila.add(("pe", name), name, contents[name])
expected[("head", name)] = wanted[name]
mycila.add(("head", name), name, contents[name])
continue
try:
stamped[name] = swap_header(contents[name], templates[header], templates[wanted[name]])
@ -1157,9 +1116,9 @@ def restamp(repo, plugin, rows, contents):
stamped |= {key[1]: content for key, content in results.items()}
skipped |= {key[1]: reason for key, reason in rejected.items()}
for name, content in stamped.items():
if ("pe", name) not in mycila.paths:
mycila.add(("pe", name), name, content)
headers = mycila.current_headers([("pe", name) for name in stamped])
if ("head", name) not in mycila.paths:
mycila.add(("head", name), name, content)
headers = mycila.current_headers([("head", name) for name in stamped])
wrong = sorted(key[1] for key, header in headers.items() if header != wanted[key[1]])
if wrong:
raise Failure(f"Restamping did not produce the expected header: {wrong[:20]}")
@ -1174,13 +1133,32 @@ def restamp(repo, plugin, rows, contents):
console.end(f"{len(stamped)} files" + (f", {len(skipped)} skipped" if skipped else ""))
def prune_curations(path, rows, orphaned):
obsolete = {row["path"]: "the check decides the same header by itself" for row in rows if row.get("redundantCuration")}
obsolete |= {row["path"]: row["reason"] for row in orphaned}
if not obsolete:
return []
data = json.loads(path.read_text(encoding="utf-8"))
data["curations"] = [entry for entry in data["curations"] if entry["path"] not in obsolete]
path.write_text(json.dumps(data, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
for row in rows:
row.pop("redundantCuration", None)
return [{"path": name, "reason": reason} for name, reason in sorted(obsolete.items())]
def check(args):
repo = repository_root()
head = resolve(repo, "HEAD")
console.begin(f"Fetching {args.ce_ref} from {args.ce_remote}")
baseline = fetch(repo, args.ce_remote, args.ce_ref)
console.end()
print_banner(repo, head, args.ce_remote, args.ce_ref, baseline)
if args.ce_ref:
console.begin(f"Fetching {args.ce_ref} from {args.ce_remote}")
baseline = fetch(repo, args.ce_remote, args.ce_ref)
console.end()
ce = {"remote": args.ce_remote, "ref": args.ce_ref, "commit": baseline}
ref_names = {baseline: args.ce_ref}
else:
ce = {"relicensingCommit": RELICENSING_COMMIT}
ref_names = {}
print_banner(repo, head, ce)
destination = report_destination(repo, args.output)
plugin = read_plugin(repo)
reject_module_overrides(repo)
@ -1188,8 +1166,9 @@ def check(args):
curation_bytes = curation_path.read_bytes()
curations = load_curations(curation_path)
console.begin("Resolving Git history")
lineage = Lineage.load(repo, head, baseline)
console.end()
bases = merged_ce_bases(repo, head, ce["commit"]) if "ref" in ce else relicensed_ce_bases(repo, head)
lineage = Lineage.load(repo, head, bases)
console.end("done (CE base " + ", ".join(ref_name(base, ref_names) for base in bases) + ")")
console.begin("Collecting Mycila scope")
scope = discover_scope(repo, plugin)
console.end(f"{len(scope.eligible)} files ({scope.ignored} Git-ignored skipped)")
@ -1200,19 +1179,21 @@ def check(args):
orphaned = [{"path": name, "status": "stale-curation", "reason": "file is no longer in scope"}
for name in sorted(set(curations) - set(scope.eligible))]
ensure_inputs_unchanged(repo, lineage, curation_path, curation_bytes, contents)
removed = []
if args.fix:
restamp(repo, plugin, rows, contents)
removed = prune_curations(curation_path, rows, orphaned)
orphaned = []
summary = Counter(row["status"] for row in rows)
result = {
"schemaVersion": 1,
"peHead": lineage.head,
"ceComparison": {"remote": args.ce_remote, "input": args.ce_ref, "commit": lineage.baseline},
"ceHistory": {"tip": lineage.baseline, "firstParent": True},
"sharedAncestor": lineage.anchor,
"peIntegrationBoundary": lineage.boundary,
"schemaVersion": 2,
"head": lineage.head,
"ce": ce | {"bases": list(lineage.bases)},
"scope": {"supported": len(scope.eligible), "unknown": scope.unknown, "modules": scope.modules},
"summary": dict(summary),
"restamped": sorted(row["path"] for row in rows if "previousHeader" in row),
"removedCurations": removed,
"redundantCurations": sorted(row["path"] for row in rows if row.get("redundantCuration")),
"curationIssues": orphaned,
"files": rows,
}
@ -1220,7 +1201,8 @@ def check(args):
destination.write_text(json.dumps(result, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
report = destination.relative_to(repo) if destination.is_relative_to(repo) else destination
print_restamped(rows)
print_findings(rows, orphaned, {baseline: args.ce_ref})
print_removed_curations(removed)
print_findings(rows, orphaned, ref_names)
print_summary(rows, orphaned, report)
return 1 if orphaned or summary.keys() - {"match"} else 0
@ -1228,14 +1210,15 @@ def check(args):
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("command", choices=["check"])
parser.add_argument("--ce-ref", required=True,
help="CE tree and first-parent history to check against; a branch, tag, or commit "
"of the CE repository, fetched from --ce-remote on every run")
parser.add_argument("--ce-ref",
help="CE branch, tag, or commit that this branch integrates, fetched from --ce-remote; "
"without it, CE is the history of HEAD that does not contain the relicensing commit")
parser.add_argument("--ce-remote", default=CE_REMOTE,
help=f"Git URL or path of the CE repository to fetch --ce-ref from (default: {CE_REMOTE})")
parser.add_argument("--output", default="target/license-provenance/report.json")
parser.add_argument("--fix", action="store_true",
help="restamp files whose expected header the check determined; unrecognized headers are kept")
help="restamp files whose expected header the check determined and remove redundant or "
"orphaned curations; unrecognized headers are kept")
args = parser.parse_args(argv)
try:
return check(args)

684
tools/src/main/python/license-headers/curations.json

File diff suppressed because it is too large

622
tools/src/main/python/license-headers/test_check_license_headers.py

@ -54,72 +54,91 @@ class GitFixture:
class DecisionTests(unittest.TestCase):
VERSION = {"path": "a.java", "ref": "b" * 40, "blob": "c" * 40}
COPY = {"path": "source.java", "ref": "a" * 40, "blob": "c" * 40, "similarity": 78}
def decide(self, **changes):
evidence = dict(path="a.java", content_hash=p.raw_hash(b"reviewed"), current="pe-only", curation=None,
inherited=True, recreated=False, ce_hash="same", pe_hash="same",
candidates=[], historical=[], in_comparison=True)
evidence = dict(path="a.java", content_hash=p.raw_hash(b"reviewed"), current=p.NON_CE,
ce_versions=(self.VERSION,), identical=self.VERSION)
return p.decide(p.Evidence(**(evidence | changes)))
def new(self, **changes):
return self.decide(**(dict(ce_versions=(), identical=None) | changes))
def test_current_header_does_not_establish_origin(self):
row = self.decide()
self.assertEqual("apache", row["expectedHeader"])
self.assertEqual("mismatch", row["status"])
self.assertEqual("ce-modified", self.decide(pe_hash="changed")["expectedHeader"])
self.assertEqual(("mismatch", "apache"), (row["status"], row["expectedHeader"]))
self.assertEqual(self.VERSION, row["identicalTo"])
row = self.decide(identical=None)
self.assertEqual(("ce-modified", "same path in CE, content differs"), (row["expectedHeader"], row["reason"]))
self.assertEqual([self.VERSION], row["ceVersions"])
def test_clean_merge_of_ce_versions_is_apache(self):
merge = {"path": "a.java", "merge": ["b" * 40, "d" * 40], "base": "e" * 40}
row = self.decide(current="apache", identical=merge)
self.assertEqual(("match", "apache"), (row["status"], row["expectedHeader"]))
self.assertEqual("same path in CE, content identical to a clean merge of its CE versions", row["reason"])
self.assertEqual(merge, row["identicalTo"])
def test_new_path_without_ce_evidence_is_non_ce(self):
row = self.new()
self.assertEqual(("match", p.NON_CE, "not in CE, no CE evidence"),
(row["status"], row["expectedHeader"], row["reason"]))
def test_ce_evidence_for_a_new_path_needs_a_decision(self):
row = self.new(copies=(self.COPY,))
self.assertEqual(("unresolved", None, None), (row["status"], row["expectedHeader"], row["suggestedHeader"]))
self.assertEqual([self.COPY], row["copyCandidates"])
self.assertEqual("apache", self.new(copies=(self.COPY | {"similarity": 100},))["suggestedHeader"])
deleted = {"path": "a.java", "ref": "f" * 40 + "^1", "blob": "c" * 40}
row = self.new(deleted=deleted)
self.assertEqual(("unresolved", "CE history had this path"), (row["status"], row["reason"]))
self.assertEqual(deleted, row["historicalCandidate"])
def test_descriptor_of_a_module_absent_in_ce_is_non_ce_despite_similar_ce_descriptors(self):
copy = self.COPY | {"path": "transport/mqtt/pom.xml"}
descriptor = dict(path="integration/mqtt/pom.xml", copies=(copy,), directory_in_ce=False)
row = self.new(**descriptor)
self.assertEqual(("match", p.NON_CE), (row["status"], row["expectedHeader"]))
for evidence in (dict(directory_in_ce=True),
dict(path="integration/mqtt/Mqtt.java"),
dict(copies=(copy | {"similarity": 100},)),
dict(deleted={"path": "integration/mqtt/pom.xml", "ref": "f" * 40, "blob": "c" * 40})):
self.assertEqual("unresolved", self.new(**(descriptor | evidence))["status"], evidence)
def test_matching_curation_precedes_inference(self):
curation = dict(contentHash=p.raw_hash(b"reviewed"), header="pe-only", reason="Independent replacement")
self.assertEqual("match", self.decide(curation=curation)["status"])
curation = dict(contentHash=p.raw_hash(b"reviewed"), header="ce-modified", reason="Reviewed")
row = self.decide(current="ce-modified", curation=curation)
self.assertEqual(("match", "ce-modified", "curation: Reviewed"),
(row["status"], row["expectedHeader"], row["reason"]))
self.assertNotIn("redundantCuration", row)
row = self.new(copies=(self.COPY,), curation=curation | {"header": p.NON_CE})
self.assertEqual(("match", p.NON_CE), (row["status"], row["expectedHeader"]))
self.assertNotIn("redundantCuration", row)
curation["contentHash"] = p.raw_hash(b"different")
self.assertEqual("stale-curation", self.decide(curation=curation)["status"])
def test_recreated_and_missing_ce_files_do_not_silently_pass(self):
self.assertEqual("unresolved", self.decide(recreated=True)["status"])
row = self.decide(inherited=False, in_comparison=False, ce_hash=None)
self.assertEqual("unresolved", row["status"])
self.assertEqual("pe-only", row["suggestedHeader"])
self.assertIsNone(row["expectedHeader"])
def test_identical_cross_path_source_is_not_proof(self):
row = self.decide(inherited=False, candidates=[{"path": "original.java"}])
self.assertEqual("unresolved", row["status"])
self.assertEqual("apache", row["suggestedHeader"])
def test_pe_additions_pass_without_strong_ce_evidence(self):
added = dict(inherited=False, in_comparison=False, ce_hash=None, pe_addition=True)
self.assertEqual("match", self.decide(**added)["status"])
self.assertEqual("match", self.decide(**added, historical=[{"path": "other/a.java"}])["status"])
for evidence in (dict(historical=[{"path": "a.java"}]),
dict(historical=[{"path": "other/a.java", "contentMatches": True}]),
dict(copies=[{"path": "other.java", "similarity": 78}])):
self.assertEqual("unresolved", self.decide(**added, **evidence)["status"])
def test_descriptor_of_a_module_absent_in_ce_is_pe_only_despite_similar_ce_descriptors(self):
descriptor = dict(path="integration/mqtt/pom.xml", inherited=False, in_comparison=False, ce_hash=None,
pe_addition=True, copies=[{"path": "transport/mqtt/pom.xml", "similarity": 78}],
directory_in_ce=False)
row = self.decide(**descriptor)
self.assertEqual("match", row["status"])
self.assertEqual("pe-only", row["expectedHeader"])
for evidence in (dict(directory_in_ce=True),
dict(path="integration/mqtt/Mqtt.java"),
dict(pe_addition=False),
dict(candidates=[{"path": "transport/mqtt/pom.xml"}]),
dict(historical=[{"path": "transport/mqtt/pom.xml", "contentMatches": True}])):
self.assertEqual("unresolved", self.decide(**(descriptor | evidence))["status"])
def test_curation_that_repeats_the_inferred_header_is_redundant(self):
curation = dict(contentHash=p.raw_hash(b"reviewed"), header="apache", reason="Reviewed")
row = self.decide(current="apache", curation=curation)
self.assertEqual(("match", "apache", "same path in CE, content identical", True),
(row["status"], row["expectedHeader"], row["reason"], row["redundantCuration"]))
row = self.new(curation=curation | {"header": p.NON_CE})
self.assertTrue(row["redundantCuration"])
def test_console_groups_findings_by_required_action(self):
missing = self.decide(current=p.MISSING)
foreign = self.decide(path="vendored.java", current=p.FOREIGN)
candidate = {"path": "original.java", "ref": "b" * 40, "blob": "c" * 40}
renamed = self.decide(path="new.java", inherited=False, candidates=[candidate, candidate])
copied = self.decide(path="copied.java", inherited=False, in_comparison=False, ce_hash=None,
copies=[{"path": "source.java", "ref": "a" * 40, "similarity": 78}])
changed = self.decide(curation=dict(contentHash=p.raw_hash(b"other"), header="pe-only", reason="Reviewed"))
copied = self.new(path="copied.java", copies=(self.COPY, self.COPY | {"path": "other.java", "similarity": 60}))
historical = self.new(path="gone.java", deleted={"path": "gone.java", "ref": "d" * 40 + "^1", "blob": "c" * 40})
changed = self.decide(curation=dict(contentHash=p.raw_hash(b"other"), header=p.NON_CE, reason="Reviewed"))
clean = self.decide(path="clean.java", current="apache")
redundant = self.decide(path="curated.java", current="apache",
curation=dict(contentHash=p.raw_hash(b"reviewed"), header="apache", reason="Reviewed"))
orphaned = dict(path="deleted.java", status="stale-curation", reason="file is no longer in scope")
stderr, stdout = io.StringIO(), io.StringIO()
with redirect_stderr(stderr), redirect_stdout(stdout):
rows = [missing, foreign, renamed, copied, changed, clean]
rows = [missing, foreign, copied, historical, changed, clean, redundant]
p.print_findings(rows, [orphaned], {"a" * 40: "ce/lts-4.2"})
p.print_summary(rows, [orphaned], "target/report.json")
output = stderr.getvalue()
@ -135,13 +154,13 @@ class DecisionTests(unittest.TestCase):
→ Rerun with --fix to restamp automatically
Needs a decision (2)
new.java
has pe-only, no expected header yet (hint: apache)
exact CE match: original.java at {"b" * 11}
another 1 candidate in the report
copied.java
has pe-only, no expected header yet
has {p.NON_CE}, no expected header yet
similar CE file (78%): source.java at ce/lts-4.2
another 1 candidate in the report
gone.java
has {p.NON_CE}, no expected header yet
CE history: gone.java at {"d" * 11}^1
→ Decide the origin and add a curation, see {p.README}
Stale curations (2)
@ -149,12 +168,31 @@ class DecisionTests(unittest.TestCase):
file changed since the curation, re-review and update contentHash
deleted.java
file is no longer in scope
→ Remove or update the entry in {p.CURATIONS}
→ Review the file and update the entry in {p.CURATIONS}; --fix removes entries of files no longer in scope
6 findings in 6 files. Report: target/report.json
Redundant curations (1)
curated.java
curated apache, the check decides apache by itself
→ Rerun with --fix to remove them from {p.CURATIONS}
6 findings in 7 files. Report: target/report.json
"""), output)
self.assertEqual("", stdout.getvalue())
def test_orphaned_curations_alone_point_to_fix(self):
orphaned = dict(path="deleted.java", status="stale-curation", reason="file is no longer in scope")
stderr = io.StringIO()
with redirect_stderr(stderr):
p.print_findings([self.decide(current="apache")], [orphaned], {})
self.assertIn(" → Rerun with --fix to remove them\n", stderr.getvalue())
def test_console_lists_removed_curations(self):
stderr = io.StringIO()
with redirect_stderr(stderr):
p.print_removed_curations([{"path": "a.java", "reason": "file is no longer in scope"}])
p.print_removed_curations([])
self.assertEqual("Removed curations (1)\n a.java\n file is no longer in scope\n\n", stderr.getvalue())
def test_console_closes_an_interrupted_phase_before_reporting(self):
stderr = io.StringIO()
with redirect_stderr(stderr):
@ -164,7 +202,7 @@ class DecisionTests(unittest.TestCase):
self.assertEqual("Resolving Git history ... failed\n\nError: boom\n", stderr.getvalue())
def test_console_summarizes_a_clean_run(self):
rows = [self.decide(current="apache"), self.decide(path="b.java", pe_hash="changed", current="ce-modified")]
rows = [self.decide(current="apache"), self.decide(path="b.java", identical=None, current="ce-modified")]
stderr = io.StringIO()
with redirect_stderr(stderr):
p.print_restamped(rows)
@ -173,7 +211,7 @@ class DecisionTests(unittest.TestCase):
"Report: target/report.json\n", stderr.getvalue())
def test_console_lists_restamped_files(self):
rows = [self.decide(current="apache"), self.decide(path="b.java", pe_hash="changed", current="ce-modified")]
rows = [self.decide(current="apache"), self.decide(path="b.java", identical=None, current="ce-modified")]
rows[1]["previousHeader"] = p.LEGACY
stderr = io.StringIO()
with redirect_stderr(stderr):
@ -297,11 +335,26 @@ class InputTests(unittest.TestCase):
write([entry])
self.assertEqual({"a.java"}, set(p.load_curations(path)))
for entries in ([entry, entry], [entry | {"reason": " "}],
[entry | {"path": "../a.java"}], [entry | {"header": "MIT"}]):
[entry | {"path": "../a.java"}], [entry | {"header": "MIT"}],
[entry | {"header": "pe-only"}]):
write(entries)
with self.assertRaises(p.Failure):
p.load_curations(path)
def test_non_ce_header_is_the_only_other_template(self):
directory = temporary_directory(self)
for name in ("license-header.txt", "license-header-ce-modified.txt", "notes.txt"):
(directory / name).write_text("header\n")
with self.assertRaises(RuntimeError):
p.non_ce_header(directory)
(directory / "license-header-busl.txt").write_text("header\n")
self.assertEqual("busl", p.non_ce_header(directory))
(directory / "license-header-pe.txt").write_text("header\n")
with self.assertRaises(RuntimeError):
p.non_ce_header(directory)
self.assertEqual(f"{p.TEMPLATE_DIRECTORY}/license-header-{p.NON_CE}.txt", p.TEMPLATES[p.NON_CE])
self.assertTrue((this_repository() / p.TEMPLATES[p.NON_CE]).is_file())
def test_plugin_version_and_configuration_come_from_root_pom(self):
repo = temporary_directory(self)
p.git(repo, "init")
@ -341,33 +394,117 @@ class GitHistoryTests(unittest.TestCase):
self.assertEqual({initial, merged}, {change.commit for change in changes})
self.assertEqual(source, changes[0].path)
git("checkout", "side")
git.write("side-only.java", "not integrated\n")
git.commit("side only")
git("checkout", "lts-4.2")
self.assertNotIn("side-only.java", {change.path for change in p.history(git.root, "HEAD")})
git("rm", source)
git.commit("delete")
deleted = p.history(git.root, "HEAD")[0]
self.assertTrue(deleted.deleted)
self.assertEqual(b"merged result\n", p.blobs(git.root, [deleted.old])[deleted.old])
def test_integration_boundary_does_not_walk_preintegration_pe_history(self):
deleted = p.history(git.root, "HEAD", "--diff-filter=D")
self.assertEqual(["D"], [change.status for change in deleted])
self.assertEqual(b"merged result\n", p.blobs(git.root, [deleted[0].old])[deleted[0].old])
def relicensed_fixture(self):
git = GitFixture(temporary_directory(self), "master")
git.write("Base.java", "base\n")
git.commit("CE base")
git("checkout", "-b", "lts-4.3")
git.write("Fix.java", "lts fix\n")
fix = git.commit("CE fix")
git("checkout", "master")
git.write("Feature.java", "CE feature\n")
last = git.commit("last Apache commit")
git.write("Tb.java", "TB feature\n")
relicensing = git.commit("relicensing")
git("merge", "--no-ff", "lts-4.3", "-m", "integrate CE fix")
return git, fix, last, relicensing
def test_relicensed_ce_bases_are_the_latest_ce_commits_merged_into_the_branch(self):
git, fix, last, relicensing = self.relicensed_fixture()
with patch.object(p, "RELICENSING_COMMIT", relicensing):
self.assertEqual(sorted([fix, last]), p.relicensed_ce_bases(git.root, git("rev-parse", "HEAD")))
git("checkout", "lts-4.3")
git.write("Fix.java", "second lts fix\n")
second = git.commit("second CE fix")
git("checkout", "master")
self.assertEqual(sorted([fix, last]), p.relicensed_ce_bases(git.root, git("rev-parse", "HEAD")))
git("merge", "--no-ff", "lts-4.3", "-m", "integrate second CE fix")
self.assertEqual(sorted([second, last]), p.relicensed_ce_bases(git.root, git("rev-parse", "HEAD")))
self.assertEqual([last], p.relicensed_ce_bases(git.root, relicensing))
def test_relicensed_ce_bases_need_the_relicensing_commit_in_history(self):
git, _, _, relicensing = self.relicensed_fixture()
with patch.object(p, "RELICENSING_COMMIT", relicensing), self.assertRaisesRegex(p.Failure, "Pass --ce-ref"):
p.relicensed_ce_bases(git.root, git("rev-parse", "lts-4.3"))
with patch.object(p, "RELICENSING_COMMIT", "0" * 40), self.assertRaisesRegex(p.Failure, "Pass --ce-ref"):
p.relicensed_ce_bases(git.root, git("rev-parse", "HEAD"))
def test_merged_ce_bases_follow_the_integrated_ce_commit(self):
git = GitFixture(temporary_directory(self), "ce")
git.write("initial", "initial")
git.commit("initial")
git("branch", "pe")
git.write("ce-file", "CE")
anchor = git.commit("CE addition")
git("checkout", "pe")
git.write("pe-file", "PE")
git.commit("PE addition")
git("merge", "ce", "-m", "CE integration")
boundary = git("rev-parse", "HEAD")
git.write("pe-file", "PE edit")
git.commit("PE edit")
self.assertEqual(boundary, p.integration_boundary(git.root, anchor, "HEAD"))
git.write("Base.java", "base\n")
git.commit("CE base")
git("checkout", "-b", "integrating")
git.write("Own.java", "own\n")
git.commit("own addition")
git("checkout", "ce")
git.write("Base.java", "CE fix\n")
integrated = git.commit("CE fix")
git("checkout", "integrating")
git("merge", "--no-ff", "ce", "-m", "integrate CE")
git("checkout", "ce")
git.write("Base.java", "later CE fix\n")
tip = git.commit("not yet integrated")
self.assertEqual([integrated], p.merged_ce_bases(git.root, git("rev-parse", "integrating"), tip))
git("checkout", "--orphan", "unrelated")
git.write("Other.java", "other\n")
unrelated = git.commit("unrelated history")
with self.assertRaisesRegex(p.Failure, "shares no history"):
p.merged_ce_bases(git.root, unrelated, tip)
def test_merged_ce_bases_below_a_relicensed_ce_ref_exclude_relicensed_commits(self):
git, fix, last, relicensing = self.relicensed_fixture()
ce_tip = git("rev-parse", "HEAD")
git("checkout", "-b", "downstream", git("rev-list", "--max-parents=0", "HEAD"))
git.write("Own.java", "own\n")
own = git.commit("own history without the relicensing commit")
git("merge", "--no-ff", "master", "-m", "integrate CE master")
head = git("rev-parse", "HEAD")
with patch.object(p, "RELICENSING_COMMIT", relicensing):
self.assertIn(own, p.relicensed_ce_bases(git.root, head))
self.assertEqual(sorted([fix, last]), p.merged_ce_bases(git.root, head, ce_tip))
def test_lineage_records_first_parent_ce_deletions(self):
git = GitFixture(temporary_directory(self), "ce")
git.write("Gone.java", "removed from CE\n")
git.write("Kept.java", "kept\n")
git.commit("CE base")
git("checkout", "-b", "side")
git.write("Temporary.java", "never on the mainline\n")
git.commit("side addition")
git("rm", "Temporary.java")
git.commit("side removal")
git("checkout", "ce")
git("merge", "--no-ff", "side", "-m", "integrate side")
git("rm", "Gone.java")
removal = git.commit("CE removal")
lineage = p.Lineage.load(git.root, removal, [removal])
self.assertEqual({"Gone.java"}, set(lineage.deleted))
self.assertEqual(removal + "^1", lineage.deleted["Gone.java"]["ref"])
self.assertEqual(b"removed from CE\n", p.blobs(git.root, [lineage.deleted["Gone.java"]["blob"]])
[lineage.deleted["Gone.java"]["blob"]])
self.assertEqual([(removal, git("rev-parse", f"{removal}:Kept.java"))], lineage.versions("Kept.java"))
self.assertEqual([], lineage.versions("Gone.java"))
def test_merge_blobs_returns_only_clean_merges(self):
git = GitFixture(temporary_directory(self), "main")
git.write("File.java", "one\ntwo\nthree\nfour\nfive\n")
git.commit("base")
base = git("rev-parse", "HEAD:File.java")
def blob(content):
git.write("File.java", content)
git.commit(content.splitlines()[0])
return git("rev-parse", "HEAD:File.java")
ours, theirs = blob("ONE\ntwo\nthree\nfour\nfive\n"), blob("one\ntwo\nthree\nfour\nFIVE\n")
self.assertEqual(b"ONE\ntwo\nthree\nfour\nFIVE\n", p.merge_blobs(git.root, ours, base, theirs))
self.assertIsNone(p.merge_blobs(git.root, ours, base, blob("uno\ntwo\nthree\nfour\nfive\n")))
def test_ignore_filter_keeps_tracked_and_unignored_files(self):
repo = temporary_directory(self)
@ -393,10 +530,10 @@ class GitHistoryTests(unittest.TestCase):
original = b"class Source {\n" + b" void action() { doUsefulWork(); }\n" * 20 + b"}\n"
tool.add(source, "Source.java", original)
tool.add(empty, "Empty.java", b"\n")
tool.add(("pe", "Renamed.java"), "Renamed.java",
tool.add(("head", "Renamed.java"), "Renamed.java",
original.replace(b"Source", b"Renamed").replace(b"\n", b"\r\n"))
tool.add(("pe", "Other.java"), "Other.java", b"independent PE implementation\n")
tool.add(("pe", "Blank.java"), "Blank.java", b"\r\n")
tool.add(("head", "Other.java"), "Other.java", b"independent implementation\n")
tool.add(("head", "Blank.java"), "Blank.java", b"\r\n")
found = p.normalized_copies(tool, {source: "selected-mainline", empty: "selected-mainline"},
["Renamed.java", "Other.java", "Blank.java"], tool.nonempty())
self.assertEqual({"Renamed.java"}, set(found))
@ -412,19 +549,19 @@ class FetchTests(unittest.TestCase):
self.ce("tag", "-a", "v4.2.0", "-m", "release")
self.ce.write("Base.java", "second\n")
self.second = self.ce.commit("second")
self.pe = GitFixture(temporary_directory(self), "pe")
self.pe.write("Pe.java", "pe\n")
self.pe.commit("pe base")
self.local = GitFixture(temporary_directory(self), "main")
self.local.write("Own.java", "own\n")
self.local.commit("own base")
def fetch(self, ref):
return p.fetch(self.pe.root, str(self.ce.root), ref)
return p.fetch(self.local.root, str(self.ce.root), ref)
def test_fetches_branches_tags_and_commits(self):
self.assertEqual(self.second, self.fetch("lts-4.2"))
self.assertEqual(self.second, self.fetch("refs/heads/lts-4.2"))
self.assertEqual(self.first, self.fetch("v4.2.0"))
self.assertEqual(self.first, self.fetch(self.first))
self.assertEqual("second", self.pe("show", f"{self.second}:Base.java"))
self.assertEqual("second", self.local("show", f"{self.second}:Base.java"))
def test_every_run_fetches_the_current_tip(self):
self.assertEqual(self.second, self.fetch("lts-4.2"))
@ -440,33 +577,39 @@ class FetchTests(unittest.TestCase):
class CheckCommandTests(unittest.TestCase):
LINES = "".join(f"line {index}\n" for index in range(10))
def setUp(self):
self.repo = temporary_directory(self)
self.git = git = GitFixture(self.repo, "lts-4.2")
self.body = "new CE feature implementation\n" * 20
git.write("Base.java", "base implementation\n")
git.commit("release base")
git("branch", "pe")
git("checkout", "-b", "fix/my-fix")
git.write("Feature.java", self.body)
git.write("Deleted.java", "historical CE feature source\n")
git.commit("CE fix sources")
git("rm", "Deleted.java")
self.feature = git.commit("remove temporary source")
git("checkout", "-b", "unrelated", "lts-4.2")
git.write("Unrelated.java", "unrelated source\n")
git.commit("unrelated source")
git("checkout", "pe")
git.write("Renamed.java", fixture("pe-only") + self.body)
git.write("Deleted.java", fixture("pe-only") + "historical CE feature source\n")
git.write("Local.java", fixture("pe-only") + "unrelated source\n")
git.write("Swapped.java", fixture("apache") + "swapped source\n")
self.git = git = GitFixture(self.repo, "master")
self.body = "CE source implementation\n" * 20
git.write(".gitignore", "target/\n")
for category, name in p.TEMPLATES.items():
git.write(name, f"fixture {category}\n")
git.write(p.CURATIONS, '{"schemaVersion": 1, "curations": []}')
git.write("Base.java", fixture("apache") + "base implementation\n")
git.write("Changed.java", fixture("apache") + "CE implementation\n")
git.write("Merged.java", fixture("apache") + self.LINES)
git.write("Source.java", fixture("apache") + self.body)
self.base = git.commit("CE base")
git("checkout", "-b", "lts-4.3")
git.write("Merged.java", fixture("apache") + self.LINES.replace("line 9", "lts fix"))
git.write("Fixed.java", fixture("apache") + "lts addition\n")
self.fix = git.commit("CE fix")
git("checkout", "master")
git.write("Deleted.java", fixture("apache") + "removed CE source\n")
self.addition = git.commit("CE addition")
git.write("Merged.java", fixture("apache") + self.LINES.replace("line 0", "master change"))
git("rm", "-q", "Deleted.java")
self.last = git.commit("last Apache commit")
git.write("Changed.java", fixture("ce-modified") + "CE implementation\nTB change\n")
git.write("New.java", fixture(p.NON_CE) + "TB feature\n")
self.relicensing = git.commit("relicensing")
git("merge", "--no-ff", "lts-4.3", "-m", "integrate CE fix")
self.scope = ["Base.java", "Changed.java", "Fixed.java", "Merged.java", "New.java", "Source.java"]
self.output = self.repo / "target/report.json"
def check(self, ref, scope, fix=False):
def check(self, *args, scope=None):
def recognized(content):
for header in p.TEMPLATES:
if content.startswith(fixture(header).encode()):
@ -483,30 +626,134 @@ class CheckCommandTests(unittest.TestCase):
def strip_headers(tool):
tool.removed = {key: split(body)[0] for key, body in tool.contents.items()}
tool.stacked = set()
return {key: p.comparison_hash(split(body)[1]) for key, body in tool.contents.items()}
for key, body in list(tool.contents.items()):
tool.write(key, split(body)[1])
return {key: p.comparison_hash(body) for key, body in tool.contents.items()}
def restamp(tool, expected):
for key, header in expected.items():
(tool.root / tool.paths[key]).write_bytes(fixture(header).encode() + split(tool.contents[key])[1])
return {key: (tool.root / tool.paths[key]).read_bytes() for key in expected}, {}
stderr = io.StringIO()
with (patch.object(p.Path, "cwd", return_value=self.repo),
patch.object(p, "RELICENSING_COMMIT", self.relicensing),
patch.object(p, "read_plugin", return_value=fixture_plugin()),
patch.object(p, "discover_scope", return_value=p.Scope(scope, [], [], 0)),
patch.object(p, "discover_scope", return_value=p.Scope(scope or self.scope, [], [], 0)),
patch.object(p.Mycila, "current_headers", current_headers),
patch.object(p.Mycila, "strip_headers", strip_headers),
patch.object(p.Mycila, "restamp", restamp),
redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO())):
code = p.main(["check", "--ce-ref", ref, "--ce-remote", str(self.repo), "--output", str(self.output)]
+ (["--fix"] if fix else []))
return code, json.loads(self.output.read_text())
redirect_stdout(io.StringIO()), redirect_stderr(stderr)):
code = p.main(["check", "--output", str(self.output), *args])
report = json.loads(self.output.read_text()) if self.output.exists() else None
return code, report, stderr.getvalue()
def test_matching_mainline_passes(self):
code, report = self.check("lts-4.2", ["Renamed.java", "Deleted.java", "Local.java"])
def rows(self, report):
return {row["path"]: row for row in report["files"]}
def test_relicensed_branch_passes(self):
code, report, _ = self.check()
self.assertEqual(0, code)
self.assertEqual({"match": 3}, report["summary"])
self.assertEqual({"remote": str(self.repo), "input": "lts-4.2", "commit": self.git("rev-parse", "lts-4.2")},
report["ceComparison"])
self.assertEqual({"match": 6}, report["summary"])
bases = sorted([self.fix, self.last])
self.assertEqual({"relicensingCommit": self.relicensing, "bases": bases}, report["ce"])
rows = self.rows(report)
self.assertEqual({"Base.java": "apache", "Changed.java": "ce-modified", "Fixed.java": "apache",
"Merged.java": "apache", "New.java": p.NON_CE, "Source.java": "apache"},
{name: row["expectedHeader"] for name, row in rows.items()})
self.assertEqual({"path": "Merged.java", "merge": bases, "base": self.base}, rows["Merged.java"]["identicalTo"])
self.assertEqual({"path": "Fixed.java", "ref": self.fix, "blob": self.git("rev-parse", f"{self.fix}:Fixed.java")},
rows["Fixed.java"]["identicalTo"])
def test_fix_restamps_decided_headers_only(self):
self.git.write("Base.java", FOREIGN_LINE.decode() + "base implementation\n")
self.git.write("New.java", fixture("apache") + "TB feature\n")
shortened = self.body.replace("CE source implementation\n", "", 1)
self.git.write("Source.java", fixture("apache") + shortened)
code, report, _ = self.check()
self.assertEqual(1, code)
self.assertEqual({"match": 3, "mismatch": 3}, report["summary"])
rows = self.rows(report)
self.assertEqual((p.FOREIGN, "apache"), (rows["Base.java"]["currentHeader"], rows["Base.java"]["expectedHeader"]))
self.assertEqual(("apache", p.NON_CE), (rows["New.java"]["currentHeader"], rows["New.java"]["expectedHeader"]))
self.assertEqual(("apache", "ce-modified"),
(rows["Source.java"]["currentHeader"], rows["Source.java"]["expectedHeader"]))
code, report, _ = self.check("--fix")
self.assertEqual(1, code)
self.assertEqual(["New.java", "Source.java"], report["restamped"])
self.assertEqual({"match": 5, "mismatch": 1}, report["summary"])
self.assertEqual(fixture(p.NON_CE) + "TB feature\n", (self.repo / "New.java").read_text())
self.assertEqual(fixture("ce-modified") + shortened, (self.repo / "Source.java").read_text())
self.assertEqual(FOREIGN_LINE.decode() + "base implementation\n", (self.repo / "Base.java").read_text())
code, report, _ = self.check("--fix")
self.assertEqual([], report["restamped"])
self.assertEqual({"match": 5, "mismatch": 1}, report["summary"])
def test_ce_evidence_for_new_paths_needs_a_decision(self):
self.git.write("Copy.java", fixture(p.NON_CE) + self.body)
self.git.write("Deleted.java", fixture(p.NON_CE) + "removed CE source\n")
code, report, output = self.check(scope=self.scope + ["Copy.java", "Deleted.java"])
self.assertEqual(1, code)
self.assertEqual({"match": 6, "unresolved": 2}, report["summary"])
rows = self.rows(report)
self.assertEqual("Source.java", rows["Copy.java"]["copyCandidates"][0]["path"])
self.assertEqual({"path": "Deleted.java", "ref": self.last + "^1",
"blob": self.git("rev-parse", f"{self.addition}:Deleted.java")},
rows["Deleted.java"]["historicalCandidate"])
self.assertIn("Needs a decision (2)\n", output)
def test_fix_removes_redundant_and_orphaned_curations(self):
self.git.write("Copy.java", fixture(p.NON_CE) + self.body)
def curation(name, header):
return dict(path=name, header=header, reason="Reviewed",
contentHash=p.raw_hash((self.repo / name).read_bytes()))
needed, redundant = curation("Copy.java", p.NON_CE), curation("New.java", p.NON_CE)
orphaned = dict(path="Gone.java", header=p.NON_CE, reason="Reviewed", contentHash=p.raw_hash(b"gone"))
self.git.write(p.CURATIONS, json.dumps(dict(schemaVersion=1, curations=[needed, redundant, orphaned]),
indent=2) + "\n")
scope = self.scope + ["Copy.java"]
code, report, output = self.check(scope=scope)
self.assertEqual(1, code)
self.assertEqual({"match": 7}, report["summary"])
self.assertEqual(["New.java"], report["redundantCurations"])
self.assertEqual([dict(path="Gone.java", status="stale-curation", reason="file is no longer in scope")],
report["curationIssues"])
self.assertIn("Redundant curations (1)\n", output)
code, report, output = self.check("--fix", scope=scope)
self.assertEqual(0, code)
self.assertEqual([{"path": "Gone.java", "reason": "file is no longer in scope"},
{"path": "New.java", "reason": "the check decides the same header by itself"}],
report["removedCurations"])
self.assertEqual(([], []), (report["redundantCurations"], report["curationIssues"]))
self.assertEqual(json.dumps(dict(schemaVersion=1, curations=[needed]), indent=2) + "\n",
(self.repo / p.CURATIONS).read_text())
self.assertIn("Removed curations (2)\n", output)
code, report, _ = self.check("--fix", scope=scope)
self.assertEqual((0, []), (code, report["removedCurations"]))
def test_missing_relicensing_commit_fails_before_the_scan(self):
self.relicensing = "0" * 40
code, report, output = self.check()
self.assertEqual((2, None), (code, report))
self.assertIn("Resolving Git history ... failed\n", output)
self.assertIn("Pass --ce-ref", output)
def test_ce_ref_mode_compares_against_the_merged_ce_commit(self):
code, report, output = self.check("--ce-ref", "lts-4.3", "--ce-remote", str(self.repo))
self.assertEqual(1, code)
self.assertEqual({"remote": str(self.repo), "ref": "lts-4.3", "commit": self.fix, "bases": [self.fix]},
report["ce"])
rows = self.rows(report)
self.assertEqual(("mismatch", "ce-modified"), (rows["Merged.java"]["status"], rows["Merged.java"]["expectedHeader"]))
self.assertEqual({"match": 5, "mismatch": 1}, report["summary"])
self.assertIn(f" CE ref lts-4.3 → {self.fix[:11]}\n", output)
self.assertIn("Resolving Git history ... done (CE base lts-4.3)\n", output)
def test_ce_ref_is_fetched_from_the_public_ce_repository_by_default(self):
fetched = []
@ -520,9 +767,9 @@ class CheckCommandTests(unittest.TestCase):
patch.object(p, "read_plugin", return_value=fixture_plugin()),
patch.object(p, "discover_scope", return_value=p.Scope([], [], [], 0)),
redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO())):
code = p.main(["check", "--ce-ref", "lts-4.2", "--output", str(self.output)])
code = p.main(["check", "--ce-ref", "lts-4.3", "--output", str(self.output)])
self.assertEqual(0, code)
self.assertEqual([(p.CE_REMOTE, "lts-4.2")], fetched)
self.assertEqual([(p.CE_REMOTE, "lts-4.3")], fetched)
def test_unfetchable_ce_ref_fails_before_the_history_walk(self):
stderr = io.StringIO()
@ -535,71 +782,6 @@ class CheckCommandTests(unittest.TestCase):
self.assertIn(f"Fetching missing from {self.repo} ... failed\n", stderr.getvalue())
self.assertIn(f"Error: cannot fetch 'missing' from {self.repo}.", stderr.getvalue())
def test_feature_ref_exposes_rename_and_history_candidates(self):
code, report = self.check("fix/my-fix", ["Renamed.java", "Deleted.java", "Local.java"])
self.assertEqual(1, code)
rows = {row["path"]: row for row in report["files"]}
self.assertEqual("unresolved", rows["Renamed.java"]["status"])
candidate = rows["Renamed.java"]["candidates"][0]
self.assertEqual(("Feature.java", self.feature), (candidate["path"], candidate["ref"]))
self.assertEqual("unresolved", rows["Deleted.java"]["status"])
self.assertTrue(rows["Deleted.java"]["historicalCandidates"])
self.assertEqual("pe-only", rows["Local.java"]["expectedHeader"])
self.assertEqual({"tip": self.feature, "firstParent": True}, report["ceHistory"])
def test_curation_for_deleted_file_fails_the_check(self):
curation = dict(path="Gone.java", contentHash=p.raw_hash(b"gone"), header="pe-only", reason="Reviewed")
self.git.write(p.CURATIONS, json.dumps(dict(schemaVersion=1, curations=[curation])))
code, report = self.check("lts-4.2", ["Renamed.java", "Deleted.java", "Local.java"])
self.assertEqual(1, code)
self.assertEqual({"match": 3}, report["summary"])
self.assertEqual([dict(path="Gone.java", status="stale-curation", reason="file is no longer in scope")],
report["curationIssues"])
def test_fix_restamps_decided_headers_only(self):
self.git("merge", "--no-ff", "fix/my-fix", "-m", "integrate CE fix")
self.git.write("Base.java", FOREIGN_LINE.decode() + "base implementation\n")
scope = ["Base.java", "Feature.java", "Renamed.java", "Swapped.java"]
code, report = self.check(self.feature, scope)
self.assertEqual(1, code)
self.assertEqual({"mismatch": 3, "unresolved": 1}, report["summary"])
self.assertEqual([], report["restamped"])
rows = {row["path"]: row for row in report["files"]}
self.assertEqual((p.FOREIGN, "apache"), (rows["Base.java"]["currentHeader"], rows["Base.java"]["expectedHeader"]))
self.assertEqual((p.MISSING, "apache"),
(rows["Feature.java"]["currentHeader"], rows["Feature.java"]["expectedHeader"]))
self.assertEqual(("apache", "pe-only"),
(rows["Swapped.java"]["currentHeader"], rows["Swapped.java"]["expectedHeader"]))
code, report = self.check(self.feature, scope, fix=True)
self.assertEqual(1, code)
self.assertEqual(["Feature.java", "Swapped.java"], report["restamped"])
self.assertEqual({"match": 2, "mismatch": 1, "unresolved": 1}, report["summary"])
rows = {row["path"]: row for row in report["files"]}
self.assertEqual(("match", "apache", p.MISSING),
(rows["Feature.java"]["status"], rows["Feature.java"]["currentHeader"],
rows["Feature.java"]["previousHeader"]))
self.assertEqual(fixture("apache") + self.body, (self.repo / "Feature.java").read_text())
self.assertEqual(fixture("pe-only") + "swapped source\n", (self.repo / "Swapped.java").read_text())
self.assertEqual("apache", rows["Swapped.java"]["previousHeader"])
self.assertEqual("mismatch", rows["Base.java"]["status"])
self.assertNotIn("previousHeader", rows["Base.java"])
self.assertEqual(FOREIGN_LINE.decode() + "base implementation\n", (self.repo / "Base.java").read_text())
self.assertEqual(fixture("pe-only") + self.body, (self.repo / "Renamed.java").read_text())
code, report = self.check(self.feature, scope, fix=True)
self.assertEqual([], report["restamped"])
self.assertEqual({"match": 2, "mismatch": 1, "unresolved": 1}, report["summary"])
def test_integrated_ce_file_compares_against_shared_ancestor(self):
self.git("merge", "--no-ff", "fix/my-fix", "-m", "integrate CE fix")
_, report = self.check(self.feature, ["Feature.java"])
self.assertEqual("apache", report["files"][0]["expectedHeader"])
self.assertEqual(self.feature, report["sharedAncestor"])
self.git.write("Feature.java", self.body + "PE-specific addition\n")
_, report = self.check(self.feature, ["Feature.java"])
self.assertEqual("ce-modified", report["files"][0]["expectedHeader"])
MANAGED_POM = textwrap.dedent("""\
<project xmlns="http://maven.apache.org/POM/4.0.0">
@ -748,30 +930,30 @@ class MavenTests(unittest.TestCase):
header = (repo / template).read_text()
for extension in SAMPLE_BODY:
for eol in ("\n", "\r\n"):
key = ("pe", category + extension + repr(eol))
key = ("head", category + extension + repr(eol))
sample = SAMPLE_PREFIX[extension] + commented(header, extension) + SAMPLE_BODY[extension]
tool.add(key, "sample." + extension, sample.replace("\n", eol).encode())
expected[key] = p.comparison_hash((SAMPLE_PREFIX[extension] + SAMPLE_BODY[extension]).encode())
missing = ("pe", "missing")
missing = ("head", "missing")
tool.add(missing, "missing.java", b"// Ordinary documentation\nclass Missing {}\n")
expected[missing] = p.comparison_hash(b"// Ordinary documentation\nclass Missing {}\n")
legacy = ("ce", "legacy")
tool.add(legacy, "legacy.java", LEGACY_JAVA)
expected[legacy] = p.comparison_hash(b"class Legacy {}\n")
foreign = ("pe", "foreign")
foreign = ("head", "foreign")
tool.add(foreign, "foreign.java", FOREIGN_LINE + b"class Foreign {}\n")
expected[foreign] = p.comparison_hash(b"class Foreign {}\n")
one_line = ("pe", "one-line")
one_line = ("head", "one-line")
tool.add(one_line, "one.sh", b"#!/bin/sh\n# Copyright 2024 The Thingsboard Authors\nset -e\necho x\n")
expected[one_line] = p.comparison_hash(b"#!/bin/sh\nset -e\necho x\n")
spdx = stamped((repo / p.TEMPLATES["apache"]).read_text(), "java").encode()
stacked = ("pe", "stacked")
stacked = ("head", "stacked")
tool.add(stacked, "stacked.java", spdx + LEGACY_JAVA)
expected[stacked] = p.comparison_hash(b"class Legacy {}\n")
reversed_stack = ("pe", "reversed")
reversed_stack = ("head", "reversed")
tool.add(reversed_stack, "reversed.java", LEGACY_JAVA.replace(b"class Legacy {}\n", spdx + b"class Legacy {}\n"))
expected[reversed_stack] = p.comparison_hash(b"class Legacy {}\n")
mentioned = ("pe", "mentioned")
mentioned = ("head", "mentioned")
tool.add(mentioned, "mentioned.java", spdx + b"\n" + FOREIGN_LINE + b"class Mentioned {}\n")
expected[mentioned] = p.comparison_hash(FOREIGN_LINE + b"class Mentioned {}\n")
pairs = {}
@ -780,18 +962,18 @@ class MavenTests(unittest.TestCase):
new = stamped((repo / p.TEMPLATES["apache"]).read_text(), extension).encode()
old = legacy_file[:-len(body)]
for order, content in (("new-old", new + old + body), ("old-new", old + new + body)):
key = ("pe", order + "." + extension)
key = ("head", order + "." + extension)
pairs[key] = content
tool.add(key, key[1], content)
expected[key] = p.comparison_hash(body)
header_only = {}
for extension in SAMPLE_BODY:
key = ("pe", "only." + extension)
header_only[key] = SAMPLE_PREFIX[extension] + commented((repo / p.TEMPLATES["pe-only"]).read_text(), extension)
key = ("head", "only." + extension)
header_only[key] = SAMPLE_PREFIX[extension] + commented((repo / p.TEMPLATES[p.NON_CE]).read_text(), extension)
tool.add(key, "only." + extension, header_only[key].encode())
expected[key] = p.comparison_hash(SAMPLE_PREFIX[extension].encode())
headers = tool.current_headers([key for key in expected if key[0] == "pe"])
headers = tool.current_headers([key for key in expected if key[0] == "head"])
recognized = dict(headers)
self.assertEqual(p.UNRECOGNIZED, headers.pop(missing))
@ -803,7 +985,7 @@ class MavenTests(unittest.TestCase):
for key in pairs:
headers.pop(key)
for key in header_only:
self.assertEqual("pe-only", headers.pop(key), key)
self.assertEqual(p.NON_CE, headers.pop(key), key)
for key, header in headers.items():
self.assertTrue(key[1].startswith(header), (key, header))
self.assertEqual(expected, tool.strip_headers())
@ -832,55 +1014,55 @@ class MavenTests(unittest.TestCase):
for extension in SAMPLE_BODY:
for eol in ("\n", "\r\n"):
body = (SAMPLE_PREFIX[extension] + SAMPLE_BODY[extension]).replace("\n", eol)
key = ("pe", "missing-" + category + extension + repr(eol))
key = ("head", "missing-" + category + extension + repr(eol))
tool.add(key, "sample." + extension, body.encode())
wanted[key] = category
expected[key] = (SAMPLE_PREFIX[extension] + stamped(header, extension) + SAMPLE_BODY[extension]).replace("\n", eol).encode()
legacy = ("pe", "legacy")
legacy = ("head", "legacy")
tool.add(legacy, "legacy.java", LEGACY_JAVA)
wanted[legacy], expected[legacy] = "apache", (stamped(templates["apache"], "java") + "class Legacy {}\n").encode()
confidential = ("pe", "confidential")
confidential = ("head", "confidential")
tool.add(confidential, "start.sh", b"#!/bin/bash\n#\n# ThingsBoard, Inc. (\"COMPANY\") CONFIDENTIAL\n#\n"
b"# Copyright \xc2\xa9 2016-2026 ThingsBoard, Inc. All Rights Reserved.\n#\n\nset -e\n")
wanted[confidential], expected[confidential] = "pe-only", ("#!/bin/bash\n" + stamped(templates["pe-only"], "sh") + "set -e\n").encode()
header_only = ("pe", "only")
wanted[confidential], expected[confidential] = p.NON_CE, ("#!/bin/bash\n" + stamped(templates[p.NON_CE], "sh") + "set -e\n").encode()
header_only = ("head", "only")
tool.add(header_only, "only.java", b"/**\n * Copyright 2024 The Thingsboard Authors\n */\n")
wanted[header_only], expected[header_only] = "ce-modified", stamped(templates["ce-modified"], "java").encode()
shebang = ("pe", "shebang")
shebang = ("head", "shebang")
tool.add(shebang, "shebang.sh", b"#!/bin/sh\n#\n# Copyright 2024 The Thingsboard Authors\n#\n")
wanted[shebang], expected[shebang] = "pe-only", ("#!/bin/sh\n" + stamped(templates["pe-only"], "sh")).encode()
glued = ("pe", "glued")
wanted[shebang], expected[shebang] = p.NON_CE, ("#!/bin/sh\n" + stamped(templates[p.NON_CE], "sh")).encode()
glued = ("head", "glued")
tool.add(glued, "glued.sh", b"#\n# Copyright 2024 The Thingsboard Authors\n#\n# helper\nset -e\n")
wanted[glued] = "pe-only"
doubled = ("pe", "doubled")
wanted[glued] = p.NON_CE
doubled = ("head", "doubled")
tool.add(doubled, "doubled.java", LEGACY_JAVA.replace(b"class Legacy {}\n", LEGACY_JAVA))
wanted[doubled], expected[doubled] = "pe-only", (stamped(templates["pe-only"], "java") + "class Legacy {}\n").encode()
damaged = ("pe", "damaged")
wanted[doubled], expected[doubled] = p.NON_CE, (stamped(templates[p.NON_CE], "java") + "class Legacy {}\n").encode()
damaged = ("head", "damaged")
tool.add(damaged, "damaged.java", stamped(templates["apache"], "java").replace("Apache-2.0", "Apache-2.0 test").encode()
+ b"class Damaged {}\n")
wanted[damaged], expected[damaged] = "apache", (stamped(templates["apache"], "java") + "class Damaged {}\n").encode()
truncated = ("pe", "truncated")
truncated = ("head", "truncated")
tool.add(truncated, "truncated.java", b"// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors\nclass Truncated {}\n")
wanted[truncated], expected[truncated] = "apache", (stamped(templates["apache"], "java") + "class Truncated {}\n").encode()
vendored = ("pe", "vendored")
vendored = ("head", "vendored")
tool.add(vendored, "vendored.java", LEGACY_JAVA.replace(b"class Legacy {}\n", FOREIGN_LINE + b"// MIT\nclass Legacy {}\n"))
wanted[vendored] = "pe-only"
wanted[vendored] = p.NON_CE
spdx = stamped(templates["apache"], "java").encode()
stacked = ("pe", "stacked")
stacked = ("head", "stacked")
tool.add(stacked, "stacked.java", spdx + LEGACY_JAVA)
wanted[stacked], expected[stacked] = "ce-modified", (stamped(templates["ce-modified"], "java") + "class Legacy {}\n").encode()
reversed_stack = ("pe", "reversed")
reversed_stack = ("head", "reversed")
tool.add(reversed_stack, "reversed.java", LEGACY_JAVA.replace(b"class Legacy {}\n", spdx + b"\nclass Legacy {}\n"))
wanted[reversed_stack], expected[reversed_stack] = "apache", (stamped(templates["apache"], "java") + "class Legacy {}\n").encode()
mentioned = ("pe", "mentioned")
mentioned = ("head", "mentioned")
tool.add(mentioned, "mentioned.java", spdx + b"\n" + FOREIGN_LINE + b"class Mentioned {}\n")
wanted[mentioned] = "pe-only"
wanted[mentioned] = p.NON_CE
for extension, legacy_file, body in (("ts", LEGACY_TS, b"export const legacy = 1;\n"),
("xml", LEGACY_XML, b"<example/>\n")):
new = stamped(templates["apache"], extension).encode()
old = legacy_file[:-len(body)]
for order, content in (("new-old", new + old + body), ("old-new", old + new + body)):
key = ("pe", order + "." + extension)
key = ("head", order + "." + extension)
tool.add(key, key[1], content)
wanted[key] = "ce-modified"
expected[key] = stamped(templates["ce-modified"], extension).encode() + body

83
ui-ngx/src/app/core/services/dashboard-utils.service.ts

@ -19,6 +19,8 @@ import {
DashboardState,
DashboardStateLayouts,
GridSettings,
htmlPageDefaultConfig,
htmlPageWidgetId,
LayoutType,
WidgetLayout
} from '@shared/models/dashboard.models';
@ -29,8 +31,10 @@ import {
isDefinedAndNotNull,
isNotEmptyStr,
isString,
isUndefined
isUndefined,
mergeDeep
} from '@core/utils';
import { htmlContainerDefaultSettings, HtmlContainerWidgetSettings } from '@shared/models/html-container.models';
import {
Datasource,
datasourcesHasAggregation,
@ -458,7 +462,7 @@ export class DashboardUtilsService {
};
}
private createDefaultGridSettings(): GridSettings {
public createDefaultGridSettings(): GridSettings {
return {
layoutType: LayoutType.default,
backgroundColor: '#eeeeee',
@ -559,6 +563,9 @@ export class DashboardUtilsService {
if (!layout.gridSettings) {
layout.gridSettings = this.createDefaultGridSettings();
}
if (!layout.widgets) {
layout.widgets = {};
}
if ((layout.gridSettings as any).margins && (layout.gridSettings as any).margins.length === 2) {
layout.gridSettings.margin = (layout.gridSettings as any).margins[0];
delete (layout.gridSettings as any).margins;
@ -650,11 +657,11 @@ export class DashboardUtilsService {
const layout: DashboardLayout = state.layouts[l];
if (layout) {
result[l]= {
default: this.getBreakpointLayoutData(layout)
default: this.getBreakpointLayoutData(layout, targetState)
};
if (layout.breakpoints) {
for (const breakpoint of Object.keys(layout.breakpoints)) {
result[l][breakpoint] = this.getBreakpointLayoutData(layout.breakpoints[breakpoint]);
result[l][breakpoint] = this.getBreakpointLayoutData(layout.breakpoints[breakpoint], targetState);
}
}
}
@ -665,17 +672,56 @@ export class DashboardUtilsService {
}
}
private getBreakpointLayoutData(layout: DashboardLayout): BreakpointLayoutInfo {
private getBreakpointLayoutData(layout: DashboardLayout, stateId: string): BreakpointLayoutInfo {
const result: BreakpointLayoutInfo = {
widgetIds: [],
widgetLayouts: {},
gridSettings: {}
};
for (const id of Object.keys(layout.widgets)) {
result.widgetIds.push(id);
if (layout.gridSettings?.layoutType === LayoutType.html) {
result.gridSettings = {
layoutType: LayoutType.html,
autoFillHeight: true,
mobileAutoFillHeight: true,
columns: 1,
minColumns: 1,
margin: 0,
outerMargin: false
};
// Stable per state: an unchanged page keeps its rendered instance, a changed one is re-rendered.
const widgetId = htmlPageWidgetId(stateId);
const config = mergeDeep({},
htmlPageDefaultConfig,
{
settings: layout.gridSettings?.htmlPageConfig?.settings || mergeDeep({} as HtmlContainerWidgetSettings, htmlContainerDefaultSettings),
actions: layout.gridSettings?.htmlPageConfig?.actions
}
);
result.widget = {
id: widgetId,
col: 0,
row: 0,
sizeX: 1,
sizeY: 1,
typeFullFqn: 'system.html_container',
type: widgetType.static,
config
};
result.widgetLayouts[widgetId] = {
col: 0,
row: 0,
sizeX: 1,
sizeY: 1,
resizable: false,
mobileOrder: 0
};
} else {
for (const id of Object.keys(layout.widgets)) {
result.widgetIds.push(id);
}
result.widgetLayouts = layout.widgets;
result.gridSettings = layout.gridSettings;
}
result.widgetLayouts = layout.widgets;
result.gridSettings = layout.gridSettings;
return result;
}
@ -691,11 +737,16 @@ export class DashboardUtilsService {
}
public isEmptyDashboard(dashboard: Dashboard): boolean {
if (dashboard?.configuration?.widgets) {
return Object.keys(dashboard?.configuration?.widgets).length === 0;
} else {
return true;
if (dashboard?.configuration?.widgets && Object.keys(dashboard.configuration.widgets).length) {
return false;
}
// An HTML page has content but no stored widgets: its widget is virtual.
return !Object.values(dashboard?.configuration?.states || {}).some(state => this.isHtmlPageState(state));
}
// A state whose widget grid is replaced by an HTML page: widgets cannot be added to it.
public isHtmlPageState(state: DashboardState): boolean {
return state?.layouts?.main?.gridSettings?.layoutType === LayoutType.html;
}
public addWidgetToLayout(dashboard: Dashboard,
@ -1273,7 +1324,11 @@ export class DashboardUtilsService {
if (layoutInfo.gridSettings) {
layout.layoutCtx.gridSettings = layoutInfo.gridSettings;
}
layout.layoutCtx.widgets.setWidgetIds(layoutInfo.widgetIds);
if (layoutInfo.widget) {
layout.layoutCtx.widgets.setWidget(layoutInfo.widget);
} else {
layout.layoutCtx.widgets.setWidgetIds(layoutInfo.widgetIds);
}
layout.layoutCtx.widgetLayouts = layoutInfo.widgetLayouts;
if (layout.show && layout.layoutCtx.ctrl) {
layout.layoutCtx.ctrl.reload();

23
ui-ngx/src/app/core/services/resources.service.ts

@ -79,6 +79,23 @@ export const componentTypeBySelector = (modulesWithComponents: ModulesWithCompon
return found?.type;
}
// The file type of a resource URL: the extension of its last path segment, or the segment itself when it is named
// after the type with an optional version, as in Google Maps' /maps/api/js and Google Fonts' /css and /css2.
const resourceFileType = (url: string, baseUrl: string): string => {
let path: string;
try {
path = new URL(url, baseUrl).pathname;
} catch {
return undefined;
}
const segment = path.substring(path.lastIndexOf('/') + 1).toLowerCase();
const extensionIndex = segment.lastIndexOf('.');
if (extensionIndex > -1) {
return segment.substring(extensionIndex + 1);
}
return /^(css|js)\d*$/.exec(segment)?.[1];
};
const matchesSelector = (selectors: ɵCssSelectorList, selector: string) =>
selectors.some(s => s.some(s1 => typeof s1 === 'string' && s1 === selector));
@ -142,11 +159,7 @@ export class ResourcesService {
return this.loadedResources[url].asObservable();
}
let fileType: string;
const match = /[./](css|less|html|htm|js)?(([?#]).*)?$/.exec(url);
if (match !== null) {
fileType = match[1];
}
const fileType = resourceFileType(url, this.document.baseURI);
if (!fileType) {
return throwError(() => new Error(`Unable to detect file type from url: ${url}`));
} else if (fileType !== 'css' && fileType !== 'js') {

25
ui-ngx/src/app/modules/home/components/attribute/add-widget-to-dashboard-dialog.component.ts

@ -1,7 +1,7 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
import { Component, Inject, OnInit, SkipSelf } from '@angular/core';
import { Component, Inject, SkipSelf } from '@angular/core';
import { ErrorStateMatcher } from '@angular/material/core';
import { MAT_DIALOG_DATA, MatDialog, MatDialogRef } from '@angular/material/dialog';
import { Store } from '@ngrx/store';
@ -16,7 +16,7 @@ import { DashboardUtilsService } from '@core/services/dashboard-utils.service';
import { EntityId } from '@app/shared/models/id/entity-id';
import { Widget } from '@app/shared/models/widget.models';
import { DashboardService } from '@core/http/dashboard.service';
import { forkJoin, Observable, of } from 'rxjs';
import { EMPTY, forkJoin, Observable, of } from 'rxjs';
import { SelectTargetLayoutDialogComponent } from '@home/components/dashboard/select-target-layout-dialog.component';
import {
SelectTargetStateDialogComponent,
@ -28,6 +28,8 @@ import { ItemBufferService } from '@core/services/item-buffer.service';
import { StateObject } from '@core/api/widget-api.models';
import { FiltersInfo } from '@shared/models/query/query.models';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { TranslateService } from '@ngx-translate/core';
import { ActionNotificationShow } from '@core/notification/notification.actions';
export interface AddWidgetToDashboardDialogData {
entityId: EntityId;
@ -44,7 +46,7 @@ export interface AddWidgetToDashboardDialogData {
})
export class AddWidgetToDashboardDialogComponent extends
DialogComponent<AddWidgetToDashboardDialogComponent, void>
implements OnInit, ErrorStateMatcher {
implements ErrorStateMatcher {
addWidgetFormGroup: UntypedFormGroup;
@ -60,7 +62,8 @@ export class AddWidgetToDashboardDialogComponent extends
private dashboardUtils: DashboardUtilsService,
private dashboardService: DashboardService,
private itembuffer: ItemBufferService,
private dialog: MatDialog) {
private dialog: MatDialog,
private translate: TranslateService) {
super(store, router, dialogRef);
this.addWidgetFormGroup = this.fb.group(
@ -95,9 +98,6 @@ export class AddWidgetToDashboardDialogComponent extends
);
}
ngOnInit(): void {
}
isErrorState(control: UntypedFormControl | null, form: FormGroupDirective | NgForm | null): boolean {
const originalErrorState = this.errorStateMatcher.isErrorState(control, form);
const customErrorState = !!(control && control.invalid && this.submitted);
@ -134,8 +134,17 @@ export class AddWidgetToDashboardDialogComponent extends
}
private selectTargetState(dashboard: Dashboard): Observable<string> {
const states = dashboard.configuration.states;
// A state with an HTML page has no widget grid to add the widget to.
const states = Object.fromEntries(Object.entries(dashboard.configuration.states)
.filter(([, state]) => !this.dashboardUtils.isHtmlPageState(state)));
const stateIds = Object.keys(states);
if (!stateIds.length) {
this.store.dispatch(new ActionNotificationShow({
message: this.translate.instant('attribute.no-widget-grid-in-dashboard'),
type: 'error'
}));
return EMPTY;
}
if (stateIds.length > 1) {
return this.dialog.open<SelectTargetStateDialogComponent, SelectTargetStateDialogData,
string>(SelectTargetStateDialogComponent, {

46
ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-page.component.html

@ -298,19 +298,35 @@
}
}
@if (isEdit) {
<button class="gt-md:!hidden" mat-icon-button
matTooltip="{{ 'dashboard.add-widget-button-text' | translate }}"
matTooltipPosition="below"
(click)="addWidget($event)">
<mat-icon>add</mat-icon>
</button>
<button class="lt-lg:!hidden" mat-stroked-button
matTooltip="{{ 'dashboard.add-widget-button-text' | translate }}"
matTooltipPosition="below"
(click)="addWidget($event)">
<mat-icon>add</mat-icon>
{{ 'dashboard.add-widget-button-text' | translate }}
</button>
@if (isHtml) {
<button class="gt-md:!hidden" mat-icon-button
matTooltip="{{ 'dashboard.edit-html-page' | translate }}"
matTooltipPosition="below"
(click)="editHtmlPage($event)">
<mat-icon>edit_document</mat-icon>
</button>
<button class="lt-lg:!hidden" mat-stroked-button
matTooltip="{{ 'dashboard.edit-html-page' | translate }}"
matTooltipPosition="below"
(click)="editHtmlPage($event)">
<mat-icon>edit</mat-icon>
{{ 'dashboard.edit-html-page' | translate }}
</button>
} @else {
<button class="gt-md:!hidden" mat-icon-button
matTooltip="{{ 'dashboard.add-widget-button-text' | translate }}"
matTooltipPosition="below"
(click)="addWidget($event)">
<mat-icon>add</mat-icon>
</button>
<button class="lt-lg:!hidden" mat-stroked-button
matTooltip="{{ 'dashboard.add-widget-button-text' | translate }}"
matTooltipPosition="below"
(click)="addWidget($event)">
<mat-icon>add</mat-icon>
{{ 'dashboard.add-widget-button-text' | translate }}
</button>
}
}
<tb-filters-edit [class.!hidden]="isEdit || !displayFilters()"
tooltipPosition="below"
@ -355,7 +371,7 @@
<section class="tb-dashboard-title"
[style.color]="dashboard.configuration.settings.titleColor">
<h3 [class.!hidden]="isEdit || !displayTitle()">{{ translatedDashboardTitle }}</h3>
<mat-form-field [class.!hidden]="!isEdit" class="mat-block tb-appearance-transparent" subscriptSizing="dynamic">
<mat-form-field [class.!hidden]="!isEdit || !displayTitle()" class="mat-block tb-appearance-transparent" subscriptSizing="dynamic">
<mat-label translate [style.color]="dashboard.configuration.settings.titleColor">dashboard.title</mat-label>
<input matInput class="tb-dashboard-title"
[style.color]="dashboard.configuration.settings.titleColor"
@ -478,7 +494,7 @@
[isReadOnly]="true"
(closeDetails)="onEditWidgetClosed()">
<div class="details-buttons flex flex-row items-center justify-start gap-4">
@if (tbEditWidget.widgetConfig?.hasBasicMode) {
@if (tbEditWidget.widgetConfig?.hasBasicMode && !isHtml) {
<tb-toggle-select appearance="fill-invert" selectMediaBreakpoint="xs" [(ngModel)]="tbEditWidget.widgetConfigMode">
<tb-toggle-option value="basic">{{ 'widget.basic-mode' | translate }}</tb-toggle-option>
<tb-toggle-option value="advanced">{{ 'widget.advanced-mode' | translate }}</tb-toggle-option>

87
ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-page.component.ts

@ -67,6 +67,7 @@ import { EntityService } from '@core/http/entity.service';
import { AliasController } from '@core/api/alias-controller';
import { BehaviorSubject, Observable, of, Subject, Subscription, throwError } from 'rxjs';
import { DashboardUtilsService } from '@core/services/dashboard-utils.service';
import { HtmlContainerWidgetSettings } from '@shared/models/html-container.models';
import { DashboardService } from '@core/http/dashboard.service';
import {
DashboardContextMenuItem,
@ -196,6 +197,10 @@ export class DashboardPageComponent extends PageComponent implements IDashboardC
return ((this.hideToolbarValue || this.hideToolbarSetting()) && !this.isEdit) || (this.isEditingWidget || this.isAddingWidget);
}
get isHtml(): boolean {
return this.layouts.main?.layoutCtx?.gridSettings?.layoutType === LayoutType.html;
}
@Input()
hideMainToolbar = true;
@ -1086,7 +1091,8 @@ export class DashboardPageComponent extends PageComponent implements IDashboardC
}
let gridSettings: GridSettings = null;
const layoutKeys = this.dashboardUtils.isSingleLayoutDashboard(this.dashboard);
if (layoutKeys) {
// An HTML page has no widget grid, so the dialog shows only the dashboard settings.
if (layoutKeys && !this.isHtml) {
const layouts = this.dashboardUtils.getDashboardLayoutConfig(
this.dashboard.configuration.states[layoutKeys.state].layouts[layoutKeys.layout],
this.layouts[layoutKeys.layout].layoutCtx.breakpoint);
@ -1114,6 +1120,7 @@ export class DashboardPageComponent extends PageComponent implements IDashboardC
this.dashboardUtils.updateLayoutSettings(layoutConfig, newGridSettings);
this.updateDashboardLayouts(layouts);
}
this.cd.markForCheck();
}
});
}
@ -1584,13 +1591,22 @@ export class DashboardPageComponent extends PageComponent implements IDashboardC
const widget = this.dashboardUtils.prepareWidgetForSaving(deepClone(this.editingWidget));
const widgetLayout = deepClone(this.editingWidgetLayout);
const id = this.editingWidgetOriginal.id;
this.dashboardConfiguration.widgets[id] = widget;
this.editingWidgetOriginal = widget;
this.editingWidgetLayoutOriginal = widgetLayout;
this.editingLayoutCtx.widgetLayouts[widget.id] = widgetLayout;
setTimeout(() => {
this.editingLayoutCtx.ctrl.highlightWidget(widget.id, 0);
}, 0);
if (this.isHtml) {
const state = this.dashboardConfiguration.states[this.dashboardCtx.state];
state.layouts.main.gridSettings.htmlPageConfig = {
settings: widget.config.settings as HtmlContainerWidgetSettings,
actions: widget.config.actions
};
this.updateLayouts();
} else {
this.dashboardConfiguration.widgets[id] = widget;
this.editingLayoutCtx.widgetLayouts[widget.id] = widgetLayout;
setTimeout(() => {
this.editingLayoutCtx.ctrl.highlightWidget(widget.id, 0);
}, 0);
}
}
onEditWidgetClosed() {
@ -1618,31 +1634,22 @@ export class DashboardPageComponent extends PageComponent implements IDashboardC
if (this.editingWidgetOriginal === widget) {
this.onEditWidgetClosed();
} else {
const transition = !this.forceDashboardMobileMode;
this.editingWidgetOriginal = widget;
this.editingWidgetLayoutOriginal = layoutCtx.widgetLayouts[widget.id];
this.editingWidget = deepClone(this.editingWidgetOriginal);
this.editingWidgetLayout = deepClone(this.editingWidgetLayoutOriginal);
this.editingLayoutCtx = layoutCtx;
this.editingWidgetSubtitle = this.widgetComponentService.getInstantWidgetInfo(this.editingWidget).widgetName;
this.forceDashboardMobileMode = true;
this.isEditingWidget = true;
this.updateLayoutSizes();
if (layoutCtx) {
const delayOffset = transition ? 350 : 0;
const delay = transition ? 400 : 300;
setTimeout(() => {
layoutCtx.ctrl.highlightWidget(widget.id, delay);
}, delayOffset);
}
this.prepareWidgetEdit(widget, layoutCtx);
}
}
editHtmlPage($event: Event) {
$event.stopPropagation();
const layoutCtx = this.layouts.main?.layoutCtx;
const widget = layoutCtx.widgets.widgetByIndex(0);
this.prepareWidgetEdit(widget, layoutCtx, '');
}
showLayoutConfigInEdit(layoutCtx: DashboardPageLayoutContext): boolean {
return layoutCtx?.gridSettings?.layoutType === LayoutType.divider ||
return layoutCtx?.gridSettings?.layoutType !== LayoutType.html && (layoutCtx?.gridSettings?.layoutType === LayoutType.divider ||
layoutCtx?.gridSettings?.layoutType === LayoutType.default &&
(layoutCtx?.breakpoint === 'default' ||
layoutCtx?.breakpoint !== 'default' && layoutCtx?.gridSettings?.viewFormat === ViewFormatType.list);
layoutCtx?.breakpoint !== 'default' && layoutCtx?.gridSettings?.viewFormat === ViewFormatType.list));
}
replaceReferenceWithWidgetCopy($event: Event, layoutCtx: DashboardPageLayoutContext, widget: Widget) {
@ -1726,14 +1733,14 @@ export class DashboardPageComponent extends PageComponent implements IDashboardC
}
widgetMouseDown($event: Event, layoutCtx: DashboardPageLayoutContext, widget: Widget) {
if (this.isEdit && !this.isEditingWidget) {
if (this.isEdit && !this.isEditingWidget && !this.isHtml) {
layoutCtx.ctrl.selectWidget(widget.id, 0);
}
}
prepareDashboardContextMenu(layoutCtx: DashboardPageLayoutContext): Array<DashboardContextMenuItem> {
const dashboardContextActions: Array<DashboardContextMenuItem> = [];
if (this.isEdit && !this.isEditingWidget && !this.widgetEditMode) {
if (this.isEdit && !this.isEditingWidget && !this.widgetEditMode && !this.isHtml) {
dashboardContextActions.push(
{
action: this.openDashboardSettings.bind(this),
@ -1788,7 +1795,7 @@ export class DashboardPageComponent extends PageComponent implements IDashboardC
prepareWidgetContextMenu(layoutCtx: DashboardPageLayoutContext, widget: Widget, isReference: boolean): Array<WidgetContextMenuItem> {
const widgetContextActions: Array<WidgetContextMenuItem> = [];
if (this.isEdit && !this.isEditingWidget) {
if (this.isEdit && !this.isEditingWidget && !this.isHtml) {
widgetContextActions.push(
{
action: (event, currentWidget) => {
@ -1952,4 +1959,28 @@ export class DashboardPageComponent extends PageComponent implements IDashboardC
private getDashboardLogoLink(): UrlTree {
return this.forceFullscreen ? null : this.router.createUrlTree([], {relativeTo: this.route});
}
private prepareWidgetEdit(widget: Widget, layoutCtx: DashboardPageLayoutContext, subtitle?: string) {
const transition = !this.forceDashboardMobileMode;
this.editingWidgetOriginal = widget;
this.editingWidgetLayoutOriginal = layoutCtx.widgetLayouts[widget.id];
this.editingWidget = deepClone(this.editingWidgetOriginal);
this.editingWidgetLayout = deepClone(this.editingWidgetLayoutOriginal);
this.editingLayoutCtx = layoutCtx;
if (isDefinedAndNotNull(subtitle)) {
this.editingWidgetSubtitle = subtitle;
} else {
this.editingWidgetSubtitle = this.widgetComponentService.getInstantWidgetInfo(this.editingWidget).widgetName;
}
this.forceDashboardMobileMode = true;
this.isEditingWidget = true;
this.updateLayoutSizes();
if (layoutCtx) {
const delayOffset = transition ? 350 : 0;
const delay = transition ? 400 : 300;
setTimeout(() => {
layoutCtx.ctrl.highlightWidget(widget.id, delay);
}, delayOffset);
}
}
}

23
ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-page.models.ts

@ -93,6 +93,8 @@ export class LayoutWidgetsArray implements Iterable<Widget> {
private widgetIds: string[] = [];
private widget: Widget;
private loaded = false;
constructor(private dashboardCtx: DashboardContext) {
@ -112,6 +114,13 @@ export class LayoutWidgetsArray implements Iterable<Widget> {
setWidgetIds(widgetIds: string[]) {
this.widgetIds = widgetIds;
this.widget = null;
this.loaded = true;
}
setWidget(widget: Widget) {
this.widget = widget;
this.widgetIds = [this.widget.id];
this.loaded = true;
}
@ -130,13 +139,19 @@ export class LayoutWidgetsArray implements Iterable<Widget> {
[Symbol.iterator](): Iterator<Widget> {
let pointer = 0;
const oneWidget = this.widget;
const widgetIds = this.widgetIds;
const dashboard = this.dashboardCtx.getDashboard();
return {
next(value?: any): IteratorResult<Widget> {
if (pointer < widgetIds.length) {
const widgetId = widgetIds[pointer++];
const widget = dashboard.configuration.widgets[widgetId];
let widget: Widget;
if (oneWidget && oneWidget.id === widgetId) {
widget = oneWidget;
} else {
widget = dashboard.configuration.widgets[widgetId];
}
return {
done: false,
value: widget
@ -161,7 +176,11 @@ export class LayoutWidgetsArray implements Iterable<Widget> {
}
private widgetById(widgetId: string): Widget {
return this.dashboardCtx.getDashboard().configuration.widgets[widgetId];
if (this.widget && this.widget.id === widgetId) {
return this.widget;
} else {
return this.dashboardCtx.getDashboard().configuration.widgets[widgetId];
}
}
}

8
ui-ngx/src/app/modules/home/components/dashboard-page/layout/dashboard-layout.component.html

@ -60,7 +60,7 @@
[aliasController]="dashboardCtx.aliasController"
[stateController]="dashboardCtx.stateController"
[dashboardTimewindow]="dashboardCtx.dashboardTimewindow"
[isEdit]="isEdit"
[isEdit]="isEdit && !isHtml"
[isEditingWidget]="isEditingWidget"
[autofillHeight]="autoFillHeight"
[mobileAutofillHeight]="mobileAutoFillHeight"
@ -68,9 +68,9 @@
[isMobile]="isMobileValue"
[isMobileDisabled]="isMobileDisabled"
[disableWidgetInteraction]="isEdit"
[isEditActionEnabled]="isEdit && !isEditingWidget"
[isExportActionEnabled]="isEdit && !widgetEditMode && !isEditingWidget"
[isRemoveActionEnabled]="isEdit && !widgetEditMode && !isEditingWidget"
[isEditActionEnabled]="isEdit && !isEditingWidget && !isHtml"
[isExportActionEnabled]="isEdit && !widgetEditMode && !isEditingWidget && !isHtml"
[isRemoveActionEnabled]="isEdit && !widgetEditMode && !isEditingWidget && !isHtml"
[callbacks]="this"
[ignoreLoading]="layoutCtx.ignoreLoading"
[parentDashboard]="parentDashboard"

36
ui-ngx/src/app/modules/home/components/dashboard-page/layout/dashboard-layout.component.ts

@ -61,16 +61,34 @@ export class DashboardLayoutComponent extends PageComponent implements ILayoutCo
return this.layoutCtx.gridSettings.layoutType === LayoutType.scada;
}
get isHtml(): boolean {
return this.layoutCtx.gridSettings.layoutType === LayoutType.html;
}
// The HTML page layout has no widget grid: its only widget is virtual and is not stored in the layout,
// so widgets cannot be copied from it, pasted into it, cut from it or referenced.
get widgetLayoutEditable(): boolean {
return this.isEdit && !this.isEditingWidget && !this.widgetEditMode && !this.isHtml;
}
get disableMargins(): boolean {
return this.isScada || this.isHtml;
}
get outerMargin(): boolean {
return this.isScada ? false : this.layoutCtx.gridSettings.outerMargin;
return this.disableMargins ? false : this.layoutCtx.gridSettings.outerMargin;
}
get margin(): number {
return this.isScada ? 0 : this.layoutCtx.gridSettings.margin;
return this.disableMargins ? 0 : this.layoutCtx.gridSettings.margin;
}
get autoFillHeight(): boolean {
return (this.isEdit || this.isScada) ? false : this.layoutCtx.gridSettings.autoFillHeight;
if (this.isHtml) {
return true;
} else {
return (this.isEdit || this.isScada) ? false : this.layoutCtx.gridSettings.autoFillHeight;
}
}
get mobileAutoFillHeight(): boolean {
@ -87,7 +105,7 @@ export class DashboardLayoutComponent extends PageComponent implements ILayoutCo
}
get isMobileDisabled(): boolean {
return this.widgetEditMode || this.isScada || (this.layoutCtx.breakpoint !== 'default' && !this.isMobileValue);
return this.widgetEditMode || this.isScada || this.isHtml || (this.layoutCtx.breakpoint !== 'default' && !this.isMobileValue);
}
get mobielRowHeigth(): number {
@ -162,7 +180,7 @@ export class DashboardLayoutComponent extends PageComponent implements ILayoutCo
private initHotKeys(): void {
this.hotKeys.push(
new Hotkey(['ctrl+c', 'meta+c'], (event: KeyboardEvent) => {
if (this.isEdit && !this.isEditingWidget && !this.widgetEditMode) {
if (this.widgetLayoutEditable) {
const widget = this.dashboard.getSelectedWidget();
if (widget) {
event.preventDefault();
@ -176,7 +194,7 @@ export class DashboardLayoutComponent extends PageComponent implements ILayoutCo
);
this.hotKeys.push(
new Hotkey(['ctrl+r', 'meta+r'], (event: KeyboardEvent) => {
if (this.isEdit && !this.isEditingWidget && !this.widgetEditMode) {
if (this.widgetLayoutEditable) {
const widget = this.dashboard.getSelectedWidget();
if (widget) {
event.preventDefault();
@ -190,7 +208,7 @@ export class DashboardLayoutComponent extends PageComponent implements ILayoutCo
);
this.hotKeys.push(
new Hotkey(['ctrl+v', 'meta+v'], (event: KeyboardEvent) => {
if (this.isEdit && !this.isEditingWidget && !this.widgetEditMode) {
if (this.widgetLayoutEditable) {
if (this.itembuffer.hasWidget()) {
event.preventDefault();
this.pasteWidget(event);
@ -203,7 +221,7 @@ export class DashboardLayoutComponent extends PageComponent implements ILayoutCo
);
this.hotKeys.push(
new Hotkey(['ctrl+i', 'meta+i'], (event: KeyboardEvent) => {
if (this.isEdit && !this.isEditingWidget && !this.widgetEditMode) {
if (this.widgetLayoutEditable) {
if (this.itembuffer.canPasteWidgetReference(this.dashboardCtx.getDashboard(),
this.dashboardCtx.state, this.layoutCtx.id, this.layoutCtx.breakpoint)) {
event.preventDefault();
@ -217,7 +235,7 @@ export class DashboardLayoutComponent extends PageComponent implements ILayoutCo
);
this.hotKeys.push(
new Hotkey(['ctrl+x', 'meta+x'], (event: KeyboardEvent) => {
if (this.isEdit && !this.isEditingWidget && !this.widgetEditMode) {
if (this.widgetLayoutEditable) {
const widget = this.dashboard.getSelectedWidget();
if (widget) {
event.preventDefault();

177
ui-ngx/src/app/modules/home/components/dashboard-page/layout/manage-dashboard-layouts-dialog.component.html

@ -29,7 +29,7 @@
</mat-select>
</mat-form-field>
</div>
@if (!isDividerLayout) {
@if (isBreakpointsLayout) {
<div class="tb-form-panel stroked">
<div class="tb-form-table tb-layout-breakpoints">
<div class="tb-form-table-header no-padding-right">
@ -85,11 +85,10 @@
<mat-icon>add</mat-icon>
</button>
</div>
} @else {
} @else if (isDividerLayout) {
<div class="flex flex-col items-center justify-start gap-5">
<mat-button-toggle-group aria-label="Select width value type"
formControlName="type"
[class.!hidden]="!isDividerLayout">
formControlName="type">
<mat-button-toggle class="flex-1" value="percentage">
{{ 'layout.percentage-width' | translate }}
</mat-button-toggle>
@ -125,7 +124,7 @@
<span [matTooltip]="layoutButtonText('main')"
#mainLayoutTooltip="matTooltip"
matTooltipPosition="above">
{{ (isDividerLayout ? 'layout.left' : 'layout.main') | translate }}
{{ 'layout.left' | translate }}
</span>
</button>
@if (showPreviewInputs('main')) {
@ -140,7 +139,55 @@
required>
}
@if (layoutsFormGroup.get('type').value === layoutWidthType.FIXED &&
layoutsFormGroup.get('fixedLayout').value === 'main') {
layoutsFormGroup.get('fixedLayout').value === 'main') {
<input
formControlName="fixedWidth"
type="number"
step="1"
min="{{ layoutFixedSize.MIN }}"
max="{{ layoutFixedSize.MAX }}"
required>
}
</div>
}
</div>
<div class="flex flex-1 flex-col items-center justify-start" matTooltip="">
<button mat-icon-button
type="button"
matTooltip="{{ 'layout.settings' | translate }}"
matTooltipPosition="above"
(click)="openLayoutSettings('right')"
class="tb-layout-preview-element"
aria-label="Layout settings"
[class]="layoutButtonClass('right')">
<mat-icon>settings</mat-icon>
</button>
<button type="button"
mat-raised-button
color="primary"
class="tb-layout-button tb-layout-button-right flex-1"
(mouseover)="rightLayoutTooltip.show()"
(mouseleave)="rightLayoutTooltip.hide()"
(click)="setFixedLayout('right')"
[class]="layoutButtonClass('right')">
<span [matTooltip]="layoutButtonText('right')"
#rightLayoutTooltip="matTooltip"
matTooltipPosition="above">
{{ 'layout.right' | translate }}
</span>
</button>
@if (showPreviewInputs('right')) {
<div class="tb-layout-preview-element tb-layout-preview-input flex-1">
@if (layoutsFormGroup.get('type').value !== layoutWidthType.FIXED) {
<input
formControlName="rightWidthPercentage"
type="number"
step="1"
min="{{ layoutPercentageSize.MIN }}"
max="{{ layoutPercentageSize.MAX }}"
required>
}
@if (layoutsFormGroup.get('type').value === layoutWidthType.FIXED) {
<input
formControlName="fixedWidth"
type="number"
@ -152,92 +199,44 @@
</div>
}
</div>
@if (isDividerLayout) {
<div class="flex flex-1 flex-col items-center justify-start" matTooltip="">
<button mat-icon-button
type="button"
matTooltip="{{ 'layout.settings' | translate }}"
matTooltipPosition="above"
(click)="openLayoutSettings('right')"
class="tb-layout-preview-element"
aria-label="Layout settings"
[class]="layoutButtonClass('right')">
<mat-icon>settings</mat-icon>
</button>
<button type="button"
mat-raised-button
color="primary"
class="tb-layout-button tb-layout-button-right flex-1"
(mouseover)="rightLayoutTooltip.show()"
(mouseleave)="rightLayoutTooltip.hide()"
(click)="setFixedLayout('right')"
[class]="layoutButtonClass('right')">
<span [matTooltip]="layoutButtonText('right')"
#rightLayoutTooltip="matTooltip"
matTooltipPosition="above">
{{ 'layout.right' | translate }}
</span>
</button>
@if (showPreviewInputs('right')) {
<div class="tb-layout-preview-element tb-layout-preview-input flex-1">
@if (layoutsFormGroup.get('type').value !== layoutWidthType.FIXED) {
<input
formControlName="rightWidthPercentage"
type="number"
step="1"
min="{{ layoutPercentageSize.MIN }}"
max="{{ layoutPercentageSize.MAX }}"
required>
}
@if (layoutsFormGroup.get('type').value === layoutWidthType.FIXED) {
<input
formControlName="fixedWidth"
type="number"
step="1"
min="{{ layoutFixedSize.MIN }}"
max="{{ layoutFixedSize.MAX }}"
required>
}
</div>
}
</div>
}
</div>
</div>
@if (isDividerLayout) {
<div class="flex flex-col items-center justify-center gap-2" style="width: 80%">
@if (layoutsFormGroup.get('type').value === layoutWidthType.PERCENTAGE) {
<mat-slider
step="1"
min="{{ layoutPercentageSize.MIN }}"
max="{{ layoutPercentageSize.MAX }}"
style="width: 100%;"
color="accent"
discrete
[displayWith]="formatSliderTooltipLabel.bind(this)"><input matSliderThumb formControlName="sliderPercentage"/>
</mat-slider>
}
@if (layoutsFormGroup.get('type').value !== layoutWidthType.PERCENTAGE) {
<mat-slider
step="1"
min="{{ layoutFixedSize.MIN }}"
max="{{ layoutFixedSize.MAX }}"
style="width: 100%;"
color="accent"
discrete
[displayWith]="formatSliderTooltipLabel.bind(this)"><input matSliderThumb formControlName="sliderFixed"/>
</mat-slider>
}
<div class="tb-hint tb-hint-group flex flex-row items-center justify-between" style="width: 100%;">
<label>
{{layoutsFormGroup.get('type').value === layoutWidthType.PERCENTAGE ? layoutPercentageSize.MIN + '%' : layoutFixedSize.MIN + 'px'}}
</label>
<label>
{{layoutsFormGroup.get('type').value === layoutWidthType.PERCENTAGE ? layoutPercentageSize.MAX + '%' : layoutFixedSize.MAX + 'px'}}
</label>
</div>
<div class="flex flex-col items-center justify-center gap-2" style="width: 80%">
@if (layoutsFormGroup.get('type').value === layoutWidthType.PERCENTAGE) {
<mat-slider
step="1"
min="{{ layoutPercentageSize.MIN }}"
max="{{ layoutPercentageSize.MAX }}"
style="width: 100%;"
color="accent"
discrete
[displayWith]="formatSliderTooltipLabel.bind(this)"><input matSliderThumb formControlName="sliderPercentage"/>
</mat-slider>
}
@if (layoutsFormGroup.get('type').value !== layoutWidthType.PERCENTAGE) {
<mat-slider
step="1"
min="{{ layoutFixedSize.MIN }}"
max="{{ layoutFixedSize.MAX }}"
style="width: 100%;"
color="accent"
discrete
[displayWith]="formatSliderTooltipLabel.bind(this)"><input matSliderThumb formControlName="sliderFixed"/>
</mat-slider>
}
<div class="tb-hint tb-hint-group flex flex-row items-center justify-between" style="width: 100%;">
<label>
{{layoutsFormGroup.get('type').value === layoutWidthType.PERCENTAGE ? layoutPercentageSize.MIN + '%' : layoutFixedSize.MIN + 'px'}}
</label>
<label>
{{layoutsFormGroup.get('type').value === layoutWidthType.PERCENTAGE ? layoutPercentageSize.MAX + '%' : layoutFixedSize.MAX + 'px'}}
</label>
</div>
}
</div>
</div>
} @else if (isHtmlLayout) {
<div class="tb-form-panel stroked h-[202px] items-center justify-center">
<div class="text-5xl font-bold text-slate-600">{{ 'dashboard.html-page' | translate }}</div>
</div>
}
</section>

86
ui-ngx/src/app/modules/home/components/dashboard-page/layout/manage-dashboard-layouts-dialog.component.ts

@ -1,5 +1,6 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
import { Component, Inject, OnDestroy, SkipSelf, ViewChild } from '@angular/core';
import { ErrorStateMatcher } from '@angular/material/core';
import { MAT_DIALOG_DATA, MatDialog, MatDialogRef } from '@angular/material/dialog';
@ -23,6 +24,7 @@ import {
DashboardLayoutId,
DashboardStateLayouts,
LayoutDimension,
HtmlPageConfig,
LayoutType,
layoutTypes,
layoutTypeTranslationMap,
@ -74,6 +76,11 @@ export class ManageDashboardLayoutsDialogComponent extends DialogComponent<Manag
layoutsFormGroup: UntypedFormGroup;
private readonly initialLayoutType: LayoutType;
// The page content of a state that starts as HTML, kept if the type is switched away and back in this dialog.
private readonly htmlPageConfig: HtmlPageConfig;
layoutWidthType = LayoutWidthType;
layoutPercentageSize = LayoutPercentageSize;
@ -113,6 +120,8 @@ export class ManageDashboardLayoutsDialogComponent extends DialogComponent<Manag
} else if (isDefined(this.layouts.main.gridSettings.layoutType)) {
layoutType = this.layouts.main.gridSettings.layoutType;
}
this.initialLayoutType = layoutType;
this.htmlPageConfig = deepClone(this.layouts.main.gridSettings.htmlPageConfig);
this.layoutsFormGroup = this.fb.group({
layoutType: [layoutType],
@ -130,6 +139,16 @@ export class ManageDashboardLayoutsDialogComponent extends DialogComponent<Manag
}
);
this.subscriptions.push(
this.layoutsFormGroup.get('layoutType').valueChanges.subscribe((value) => {
if (value !== LayoutType.html && this.layouts.main.gridSettings.htmlPageConfig) {
// Leaving the HTML page: start the widget grid from the defaults right away, so that layout settings
// and new breakpoints copied from the main layout are based on them.
this.layouts.main.gridSettings = this.dashboardUtils.createDefaultGridSettings();
}
})
);
this.subscriptions.push(
this.layoutsFormGroup.get('type').valueChanges.subscribe(
(value) => {
@ -184,7 +203,7 @@ export class ManageDashboardLayoutsDialogComponent extends DialogComponent<Manag
this.addLayoutConfiguration('default');
if (!this.isDividerLayout && this.layouts.main.breakpoints) {
if (this.isBreakpointsLayout && this.layouts.main.breakpoints) {
for (const breakpoint of (Object.keys(this.layouts.main.breakpoints) as BreakpointId[])) {
this.addLayoutConfiguration(breakpoint);
this.selectedBreakpointIds.push(breakpoint);
@ -276,10 +295,28 @@ export class ManageDashboardLayoutsDialogComponent extends DialogComponent<Manag
save(): void {
this.submitted = true;
const removedWidgetsCount = this.isHtmlLayout && this.initialLayoutType !== LayoutType.html ? this.countLayoutWidgets() : 0;
if (removedWidgetsCount) {
this.dialogs.confirm(
this.translate.instant('layout.switch-to-html-page-title'),
this.translate.instant('layout.switch-to-html-page-text', {count: removedWidgetsCount}),
this.translate.instant('action.no'),
this.translate.instant('action.yes')
).subscribe((res) => {
if (res) {
this.applyLayouts();
}
});
} else {
this.applyLayouts();
}
}
private applyLayouts(): void {
const layoutType = this.layoutsFormGroup.value.layoutType;
this.layouts.main.gridSettings.layoutType = layoutType;
if (!this.isDividerLayout) {
delete this.layouts.right;
delete this.layouts.main.gridSettings.layoutDimension;
if (this.isBreakpointsLayout) {
if (this.layouts.main.breakpoints) {
for (const breakpoint of Object.values(this.layouts.main.breakpoints)) {
breakpoint.gridSettings.layoutType = layoutType;
@ -287,13 +324,10 @@ export class ManageDashboardLayoutsDialogComponent extends DialogComponent<Manag
}
} else {
delete this.layouts.main.breakpoints;
this.layouts.right.gridSettings.layoutType = layoutType;
}
delete this.layouts.main.gridSettings.layoutDimension;
if (this.layouts.right?.gridSettings) {
delete this.layouts.right.gridSettings.layoutDimension;
}
if (this.isDividerLayout) {
this.layouts.right.gridSettings.layoutType = layoutType;
delete this.layouts.right.gridSettings.layoutDimension;
const formValues = this.layoutsFormGroup.value;
const widthType = formValues.type;
const layoutDimension: LayoutDimension = {
@ -311,6 +345,19 @@ export class ManageDashboardLayoutsDialogComponent extends DialogComponent<Manag
this.layouts.right.gridSettings.layoutDimension = layoutDimension;
}
}
} else {
delete this.layouts.right;
}
if (this.isHtmlLayout) {
// An empty widgets map rather than none: code that walks layouts keeps working with HTML pages.
this.layouts.main.widgets = {};
this.layouts.main.gridSettings = {
layoutType: LayoutType.html,
htmlPageConfig: {
settings: this.htmlPageConfig?.settings,
actions: this.htmlPageConfig?.actions
}
};
}
this.dialogRef.close(this.layouts);
}
@ -414,6 +461,27 @@ export class ManageDashboardLayoutsDialogComponent extends DialogComponent<Manag
return this.layoutsFormGroup.get('layoutType').value === LayoutType.divider;
}
// Widgets placed in the state's layouts, which the HTML page replaces.
private countLayoutWidgets(): number {
const widgetIds = new Set<string>();
const layouts = [this.layouts.main, ...Object.values(this.layouts.main?.breakpoints || {})];
if (this.initialLayoutType === LayoutType.divider) {
layouts.push(this.layouts.right);
}
for (const layout of layouts) {
Object.keys(layout?.widgets || {}).forEach(id => widgetIds.add(id));
}
return widgetIds.size;
}
get isHtmlLayout(): boolean {
return this.layoutsFormGroup.get('layoutType').value === LayoutType.html;
}
get isBreakpointsLayout(): boolean {
return [LayoutType.default, LayoutType.scada].includes(this.layoutsFormGroup.get('layoutType').value);
}
addBreakpoint() {
this.dialog.open<AddNewBreakpointDialogComponent, AddNewBreakpointDialogData,
AddNewBreakpointDialogResult>(AddNewBreakpointDialogComponent, {

8
ui-ngx/src/app/modules/home/components/widget/config/basic/chart/comparison-keys-table.component.html

@ -1,8 +0,0 @@
<!--
SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
-->
-->

8
ui-ngx/src/app/modules/home/components/widget/config/basic/html/html-container-basic-config.component.ts

@ -1,5 +1,6 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
import { Component, HostBinding } from '@angular/core';
import { UntypedFormBuilder, UntypedFormGroup } from '@angular/forms';
import { Store } from '@ngrx/store';
@ -7,10 +8,7 @@ import { AppState } from '@core/core.state';
import { BasicWidgetConfigComponent } from '@home/components/widget/config/widget-config.component.models';
import { WidgetConfigComponentData } from '@home/models/widget-component.models';
import { WidgetConfigComponent } from '@home/components/widget/widget-config.component';
import {
htmlContainerDefaultSettings,
HtmlContainerWidgetSettings
} from '@home/components/widget/lib/html/html-container-widget.models';
import { htmlContainerDefaultSettings, HtmlContainerWidgetSettings } from '@shared/models/html-container.models';
@Component({
selector: 'tb-html-container-basic-config',

11
ui-ngx/src/app/modules/home/components/widget/lib/html/html-container-widget.component.ts

@ -1,5 +1,6 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
import {
ChangeDetectorRef,
Component, ComponentRef,
@ -16,9 +17,6 @@ import {
} from '@angular/core';
import { WidgetContext } from '@home/models/widget-component.models';
import {
htmlContainerDefaultSettings,
HtmlContainerWidgetSettings,
HtmlContainerWidgetType,
WidgetContainerAngularFunction,
WidgetContainerPlainFunction
} from '@home/components/widget/lib/html/html-container-widget.models';
@ -40,6 +38,11 @@ import {
import { MODULES_MAP } from '@shared/models/constants';
import { IModulesMap } from '@modules/common/modules-map.models';
import { TbAnchorComponent } from '@shared/components/tb-anchor.component';
import {
htmlContainerDefaultSettings,
HtmlContainerWidgetSettings,
HtmlContainerWidgetType
} from '@shared/models/html-container.models';
@Component({
selector: 'tb-html-container-widget',

28
ui-ngx/src/app/modules/home/components/widget/lib/html/html-container-widget.models.ts

@ -1,31 +1,13 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
import { TbFunction } from '@shared/models/js-function.models';
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
import { WidgetContext } from '@home/models/widget-component.models';
import { TbEditorCompleter, TbEditorCompletions } from '@shared/models/ace/completion.models';
import { widgetContextCompletions } from '@shared/models/ace/widget-completion.models';
import { WidgetResource } from '@shared/models/widget.models';
export enum HtmlContainerWidgetType {
PLAIN = 'PLAIN',
ANGULAR = 'ANGULAR'
}
export interface HtmlContainerWidgetSettings {
type: HtmlContainerWidgetType;
html: string;
css: string;
js: TbFunction;
resources: WidgetResource[];
}
export const htmlContainerDefaultSettings: HtmlContainerWidgetSettings = {
type: HtmlContainerWidgetType.PLAIN,
html: '',
css: '',
js: '',
resources: [],
};
// Moved to @shared/models/html-container.models (the HTML page layout uses them too); re-exported for existing imports.
export { HtmlContainerWidgetType, htmlContainerDefaultSettings } from '@shared/models/html-container.models';
export type { HtmlContainerWidgetSettings } from '@shared/models/html-container.models';
export type WidgetContainerPlainFunction = (ctx: WidgetContext, container: HTMLElement) => void;
export type WidgetContainerAngularFunction = (ctx: WidgetContext) => void;

6
ui-ngx/src/app/modules/home/components/widget/lib/settings/common/html/html-container-settings.component.ts

@ -1,5 +1,6 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
import {
AfterViewInit,
Component,
@ -27,12 +28,11 @@ import {
import {
AngularContainerFunctionEditorCompleter,
HTMLContainerFunctionEditorCompleter,
HtmlContainerWidgetSettings,
HtmlContainerWidgetType
} from '@home/components/widget/lib/html/html-container-widget.models';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { isJSResource } from '@shared/models/resource.models';
import { WidgetService } from '@core/http/widget.service';
import { HtmlContainerWidgetSettings, HtmlContainerWidgetType } from '@shared/models/html-container.models';
@Component({
selector: 'tb-html-container-settings',

5
ui-ngx/src/app/modules/home/components/widget/lib/settings/html/html-container-widget-settings.component.ts

@ -1,11 +1,12 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
import { Component, HostBinding } from '@angular/core';
import { WidgetSettings, WidgetSettingsComponent } from '@shared/models/widget.models';
import { UntypedFormBuilder, UntypedFormGroup } from '@angular/forms';
import { Store } from '@ngrx/store';
import { AppState } from '@core/core.state';
import { htmlContainerDefaultSettings } from '@home/components/widget/lib/html/html-container-widget.models';
import { htmlContainerDefaultSettings } from '@shared/models/html-container.models';
@Component({
selector: 'tb-html-container-widget-settings',

3
ui-ngx/src/app/modules/home/components/widget/widget-container.component.ts

@ -321,6 +321,9 @@ export class WidgetContainerComponent extends PageComponent implements OnInit, O
const container = parent.getBoundingClientRect();
position.coord.left = Math.max(0,clientRect.right - position.size.width - container.left);
position.coord.top = position.coord.top - container.top;
if (position.coord.top < 2) {
position.coord.top = 2;
}
position.target = clientRect.right;
return position;
},

3
ui-ngx/src/app/modules/home/pages/admin/resource/js-resource.component.ts

@ -1,6 +1,5 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
// SPDX-License-Identifier: Apache-2.0
import { ChangeDetectorRef, Component, Inject, OnDestroy, OnInit } from '@angular/core';
import { Subject } from 'rxjs';
import { Store } from '@ngrx/store';

8
ui-ngx/src/app/modules/home/pages/admin/trendz-settings.component.html

@ -1,8 +0,0 @@
<!--
SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
-->
-->

29
ui-ngx/src/app/shared/models/dashboard.models.ts

@ -5,13 +5,14 @@ import { BaseData, ExportableEntity, GroupEntityInfo } from '@shared/models/base
import { DashboardId } from '@shared/models/id/dashboard-id';
import { TenantId } from '@shared/models/id/tenant-id';
import { ShortCustomerInfo } from '@shared/models/customer.model';
import { Widget } from './widget.models';
import { Widget, WidgetActionsMap, WidgetConfig, WidgetConfigMode } from './widget.models';
import { Timewindow } from '@shared/models/time/time.models';
import { EntityAliases } from './alias.models';
import { CustomerId } from '@shared/models/id/customer-id';
import { Filters } from '@shared/models/query/query.models';
import { MatDialogRef } from '@angular/material/dialog';
import { HasTenantId, HasVersion } from '@shared/models/entity.models';
import { HtmlContainerWidgetSettings } from '@shared/models/html-container.models';
export interface WidgetLayout {
sizeX?: number;
@ -34,6 +35,7 @@ export enum LayoutType {
default = 'default',
scada = 'scada',
divider = 'divider',
html = 'html'
}
export const layoutTypes = Object.keys(LayoutType) as LayoutType[];
@ -43,6 +45,7 @@ export const layoutTypeTranslationMap = new Map<LayoutType, string>(
[ LayoutType.default, 'dashboard.layout-type-default' ],
[ LayoutType.scada, 'dashboard.layout-type-scada' ],
[ LayoutType.divider, 'dashboard.layout-type-divider' ],
[ LayoutType.html, 'dashboard.layout-type-html' ]
]
);
@ -60,6 +63,27 @@ export const viewFormatTypeTranslationMap = new Map<ViewFormatType, string>(
]
);
export const htmlPageDefaultConfig: WidgetConfig = {
showTitle: false,
backgroundColor: 'rgba(255, 255, 255, 0)',
color: 'rgba(0, 0, 0, 0.87)',
padding: '0',
dropShadow: false,
enableFullscreen: false,
widgetStyle: {},
title: 'HTML page',
configMode: WidgetConfigMode.basic
};
export interface HtmlPageConfig {
settings: HtmlContainerWidgetSettings;
actions?: WidgetActionsMap;
}
// Id of the virtual HTML Container widget that renders a state's HTML page. It is never stored in
// dashboard.configuration.widgets, so it cannot collide with a widget id there.
export const htmlPageWidgetId = (stateId: string): string => `html-page-${stateId}`;
export interface GridSettings {
layoutType?: LayoutType;
backgroundColor?: string;
@ -76,6 +100,8 @@ export interface GridSettings {
mobileRowHeight?: number;
mobileDisplayLayoutFirst?: boolean;
layoutDimension?: LayoutDimension;
// For LayoutType.html
htmlPageConfig?: HtmlPageConfig;
}
export interface DashboardLayout {
@ -90,6 +116,7 @@ export interface BreakpointLayoutInfo {
widgetIds?: string[];
widgetLayouts?: WidgetLayouts;
gridSettings?: GridSettings;
widget?: Widget;
}
export declare type BreakpointSystemId = 'default' | 'xs' | 'sm' | 'md' | 'lg' | 'xl';

25
ui-ngx/src/app/shared/models/html-container.models.ts

@ -0,0 +1,25 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
import { TbFunction } from '@shared/models/js-function.models';
import { WidgetResource } from '@shared/models/widget.models';
export enum HtmlContainerWidgetType {
PLAIN = 'PLAIN',
ANGULAR = 'ANGULAR'
}
export interface HtmlContainerWidgetSettings {
type: HtmlContainerWidgetType;
html: string;
css: string;
js: TbFunction;
resources: WidgetResource[];
}
export const htmlContainerDefaultSettings: HtmlContainerWidgetSettings = {
type: HtmlContainerWidgetType.PLAIN,
html: '',
css: '',
js: '',
resources: [],
};

6
ui-ngx/src/assets/locale/locale.constant-en_US.json

@ -1067,6 +1067,7 @@
"prev-widget": "Previous widget",
"add-to-dashboard": "Add to dashboard",
"add-widget-to-dashboard": "Add widget to dashboard",
"no-widget-grid-in-dashboard": "All states of this dashboard are HTML pages, so the widget cannot be added to it.",
"selected-attributes": "{ count, plural, =1 {1 attribute} other {# attributes} } selected",
"selected-telemetry": "{ count, plural, =1 {1 telemetry unit} other {# telemetry units} } selected",
"no-attributes-text": "No attributes found",
@ -2375,6 +2376,8 @@
"no-widgets": "No widgets configured",
"add-widget": "Add new widget",
"add-widget-button-text": "Add widget",
"edit-html-page": "Edit HTML page",
"html-page": "HTML page",
"title": "Title",
"image": "Dashboard image",
"mobile-app-settings": "Mobile application settings",
@ -2448,6 +2451,7 @@
"layout-type-default": "Default",
"layout-type-scada": "SCADA",
"layout-type-divider": "Divider",
"layout-type-html": "HTML Page",
"layout-settings-type": "Layout settings: {{ type }} breakpoint",
"columns-count": "Columns count",
"columns-count-required": "Columns count is required.",
@ -6573,6 +6577,8 @@
"no-data": "No entries"
},
"layout": {
"switch-to-html-page-title": "Switch to HTML page?",
"switch-to-html-page-text": "The HTML page replaces the widget grid of this state. { count, plural, =1 {1 widget} other {# widgets} } placed in its layouts will be removed from this state.",
"layout": "Layout",
"layouts": "Layouts",
"manage": "Manage layouts",

Loading…
Cancel
Save