Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 36 additions & 1 deletion eslint.config.mjs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2025 Ping Identity Corporation. All rights reserved.
* Copyright (c) 2025 - 2026 Ping Identity Corporation. All rights reserved.
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
Expand Down Expand Up @@ -33,6 +33,41 @@ export default [
'**/test-output',
],
},
{
files: ['**/*.ts', '**/*.tsx', '**/*.js', '**/*.jsx', '**/*.mjs', '**/*.cjs'],
ignores: ['**/vite.config.*', '**/vitest.config.*', '**/vitest.setup.*', '**/eslint.config.*'],
plugins: {
'local-rules': {
rules: {
'ping-copyright': {
meta: {
type: 'suggestion',
messages: { missing: 'Missing Ping Identity copyright header.' },
},
create(context) {
return {
Program(node) {
const src = context.getSourceCode();
const comments = src.getAllComments();
const first = comments[0];
if (
!first ||
first.range[0] > 0 ||
!/Copyright[\s\S]*Ping Identity/i.test(first.value)
) {
context.report({ node, messageId: 'missing' });
}
},
};
},
},
},
},
},
rules: {
'local-rules/ping-copyright': 'warn',
},
},
...compat.extends('plugin:@typescript-eslint/recommended', 'plugin:prettier/recommended'),
{
plugins: {
Expand Down
3 changes: 3 additions & 0 deletions lefthook.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ pre-commit:
commands:
nx-sync:
run: pnpm nx sync
copyright-sync:
run: node tools/copyright/sync-header-years.mjs --fix
stage_fixed: true
nx-check:
run: pnpm nx affected -t typecheck lint build api-report --tui=false
stage_fixed: true
Expand Down
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@
"circular-dep-check": "madge --circular .",
"clean": "shx rm -rf ./{coverage,dist,docs,node_modules,tmp}/ ./{packages,e2e}/*/{dist,node_modules}/ ./e2e/node_modules/ && git clean -fX -e \"!.env*,nx-cloud.env\" -e \"!**/GEMINI.md\"",
"commit": "git cz",
"copyright:check": "node tools/copyright/sync-header-years.mjs --check",
"copyright:sync": "node tools/copyright/sync-header-years.mjs --fix",
"commitlint": "commitlint --edit",
"create-package": "nx g @nx/js:library",
"format": "pnpm nx format:write",
Expand Down
4 changes: 2 additions & 2 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

172 changes: 172 additions & 0 deletions tools/copyright/sync-header-years.mjs

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is almost 200 lines of code. It seems like we have separate logic for --check and --fix. We can combine those two and only apply --fix with updateCopyrightYears. We have to perform the same validation whether we call the --check or --fix, the only difference is with --fix we also need to call updateCopyrightYears.

Some code optimizations:

  1. Merge hasPingCopyrightHeader (171–179) into hasInvalidPingCopyrightHeader (155–168)
    Both functions iterate lines and test MAYBE_PING_COPYRIGHT_LINE_REGEX + HEADER_COMMENT_LINE_REGEX. The only difference: one returns true when the header is present, the other returns true when it's present but invalid. One function returning { present, valid } replaces both.

  2. Collapse three loops (22–35, 46–58, 60–69) into one
    Right now run() builds stagedFileData in the first loop, then loops over it again for missing headers, then again for year updates. All three can run in a single for loop — read the file, check invalid format, check missing header, compute updated content — then branch once at the end based on checkOnly.

  3. Inline isFile (112–118) and safeReadUtf8 (120–126)
    Each is called exactly once. isFile is 3 lines of real logic, safeReadUtf8 is 3 lines. Not worth a named function.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good call! I applied the changes you suggested. Merged the two header-check helpers into one inspectPingCopyrightHeader that returns { present, invalid } and collapsed the three loops into one.
Thanks for the suggestions!

Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
#!/usr/bin/env node

import { execFileSync } from 'node:child_process';
import { readFileSync, statSync, writeFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { pathToFileURL } from 'node:url';

function isCliExecution() {
return process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href;
}

function run() {
const args = new Set(process.argv.slice(2));
const checkOnly = args.has('--check');
const currentYear = new Date().getFullYear();

const stagedFileData = [];
const invalidFiles = [];
const missingHeaderFiles = [];
const changedFiles = [];

for (const file of getStagedFiles()) {
if (isExcluded(file)) {
continue;
}

let original;
try {
if (!statSync(resolve(process.cwd(), file)).isFile()) {
continue;
}
original = readFileSync(resolve(process.cwd(), file), 'utf8');
} catch {
continue;
}

const absolutePath = resolve(process.cwd(), file);
const { present, invalid } = inspectPingCopyrightHeader(original);

if (invalid) {
invalidFiles.push(file);
}
if (SOURCE_FILE_PATTERN.test(file) && !present) {
missingHeaderFiles.push(file);
}

const updated = updateCopyrightYears(original, currentYear);
if (updated !== original) {
changedFiles.push(file);
}
stagedFileData.push({ file, absolutePath, updated });
}

if (invalidFiles.length > 0) {
console.error('Invalid Ping copyright header year format in staged files:');
for (const file of invalidFiles) {
console.error(`- ${file}`);
}
process.exit(1);
}

if (checkOnly) {
if (missingHeaderFiles.length > 0) {
console.error('Missing Ping copyright header in staged files:');
for (const file of missingHeaderFiles) {
console.error(`- ${file}`);
}
process.exit(1);
}
if (changedFiles.length > 0) {
console.error('Stale Ping copyright years found in staged files:');
for (const file of changedFiles) {
console.error(`- ${file}`);
}
process.exit(1);
}
return;
}

for (const { file, absolutePath, updated } of stagedFileData) {
if (changedFiles.includes(file)) {
writeFileSync(absolutePath, updated, 'utf8');
}
}

if (changedFiles.length > 0) {
execFileSync('git', ['add', '--', ...changedFiles], { stdio: 'inherit' });
}
}

function getStagedFiles() {
const output = execFileSync('git', ['diff', '--cached', '--name-only', '--diff-filter=ACMR'], {
encoding: 'utf8',
}).trim();

if (!output) {
return [];
}
return output.split('\n').filter(Boolean);
}

export function isExcluded(filePath) {
return EXCLUDE_PATTERNS.some((pattern) => pattern.test(filePath));
}

const EXCLUDE_PATTERNS = [
/(^|[/\\])dist[/\\]/,
/(^|[/\\])vendor[/\\]/,
/(^|[/\\])node_modules[/\\]/,
/(^|[/\\])tools[/\\]/,
/(^|[/\\])_polyfills[/\\]/,
/(^|[/\\])vite[^/\\]*\.config\.[cm]?[jt]sx?$/i,
/(^|[/\\])vitest\.setup\.[cm]?[jt]sx?$/i,
/(^|[/\\])playwright\.config\.[cm]?[jt]sx?$/i,
];

export function updateCopyrightYears(content, year) {
const regex =
/(^.*(?:©\s*|©\s*)?Copyright(?:\s*\(c\))?\s+)(\d{4})(?:([ \t]*-[ \t]*)(\d{4}))?(\s+Ping Identity(?: Corporation)?\b.*$)/gim;

return content.replace(regex, (_, prefix, startYear, separator, endYear, suffix) => {
const start = Number.parseInt(startYear, 10);
const end = endYear ? Number.parseInt(endYear, 10) : start;

if (Number.isNaN(start) || Number.isNaN(end)) {
return `${prefix}${startYear}${endYear ? `${separator}${endYear}` : ''}${suffix}`;
}

const resolvedEnd = end >= year ? end : year;

if (!endYear) {
// Single year already current — no range needed
if (resolvedEnd === start) {
return `${prefix}${startYear}${suffix}`;
}
return `${prefix}${startYear} - ${resolvedEnd}${suffix}`;
}

// Always normalize separator to ' - ' and bump end year when stale
return `${prefix}${startYear} - ${resolvedEnd}${suffix}`;
});
}

export function inspectPingCopyrightHeader(content) {
const lines = content.split(/\r?\n/);
let present = false;
let invalid = false;

for (const line of lines) {
if (!MAYBE_PING_COPYRIGHT_LINE_REGEX.test(line) || !HEADER_COMMENT_LINE_REGEX.test(line)) {
continue;
}
present = true;
if (!VALID_PING_COPYRIGHT_LINE_REGEX.test(line)) {
invalid = true;
}
}

return { present, invalid };
}

const SOURCE_FILE_PATTERN = /\.[cm]?[jt]sx?$/i;

const MAYBE_PING_COPYRIGHT_LINE_REGEX =
/(?:©\s*|©\s*)?Copyright(?:\s*\(c\))?.*Ping Identity(?: Corporation)?/i;
const HEADER_COMMENT_LINE_REGEX = /^\s*(?:\/\*+|\*+|\/\/+|#+|<!--)\s*/;
const VALID_PING_COPYRIGHT_LINE_REGEX =
/^.*(?:©\s*|&copy;\s*)?Copyright(?:\s*\(c\))?\s+\d{4}(?:[ \t]*-[ \t]*\d{4})?\s+Ping Identity(?: Corporation)?\b.*$/i;

if (isCliExecution()) {
run();
}
Loading
Loading