@bernierllc/license-manager
v0.1.0
Published
Pure license management utilities for adding and validating license headers
Downloads
82
Readme
@bernierllc/license-manager
Pure license management utilities for adding and validating license headers across different file types.
Features
- File Type Detection: Automatically detects file types and applies appropriate license formats
- Multiple License Formats: Supports C-style comments, Python docstrings, HTML comments, and more
- License Validation: Validates existing license headers for compliance
- Directory Scanning: Scans entire directories for license compliance
- Customizable Templates: Configurable license templates and file type mappings
- Dry Run Mode: Preview changes without modifying files
- Comprehensive Testing: Full test coverage with mocked file system
Installation
npm install @bernierllc/license-managerQuick Start
import { LicenseManager } from '@bernierllc/license-manager';
const licenseManager = new LicenseManager();
// Add license header to a file
const success = licenseManager.addLicenseHeader('src/my-file.js');
// Validate existing license header
const validation = licenseManager.validateLicenseHeader('src/my-file.js');
console.log('Has license:', validation.hasLicense);
console.log('Is valid:', validation.isValid);
// Scan directory for compliance
const scanResult = licenseManager.scanDirectory('./src');
console.log('Compliance rate:', scanResult.complianceRate);API Reference
LicenseManager
Main class for license management operations.
Constructor
new LicenseManager(config?: Partial<LicenseTemplateConfig>)Creates a new license manager instance with optional custom configuration.
Methods
detectFileType(filePath: string): FileType
Detects the file type based on file extension.
const fileType = licenseManager.detectFileType('src/component.tsx');
// Returns: 'tsx'getLicenseTemplate(fileType: FileType, options?: LicenseHeaderOptions): LicenseTemplate
Gets the appropriate license template for a file type.
const template = licenseManager.getLicenseTemplate('js', {
copyrightYear: 2024,
companyName: 'My Company'
});generateLicenseHeader(filePath: string, options?: LicenseHeaderOptions): string
Generates a license header for a specific file.
const header = licenseManager.generateLicenseHeader('src/file.js');
// Returns: "/*\nCopyright (c) 2025 Bernier LLC\n...\n*/\n\n"validateLicenseHeader(filePath: string, options?: LicenseHeaderOptions): LicenseValidationResult
Validates if a file has the correct license header.
const result = licenseManager.validateLicenseHeader('src/file.js');
console.log(result.hasLicense); // boolean
console.log(result.isValid); // boolean
console.log(result.errors); // string[]addLicenseHeader(filePath: string, options?: LicenseHeaderOptions): boolean
Adds a license header to a file if it doesn't already have one.
const success = licenseManager.addLicenseHeader('src/file.js', {
dryRun: true // Preview without writing
});scanDirectory(dirPath: string, options?: LicenseHeaderOptions): LicenseScanResult
Scans a directory for license compliance.
const result = licenseManager.scanDirectory('./src');
console.log(`Compliance: ${result.complianceRate}%`);
console.log(`Files with license: ${result.filesWithLicense}`);
console.log(`Files missing license: ${result.filesWithoutLicense}`);getConfig(): LicenseTemplateConfig
Returns the current configuration.
updateConfig(newConfig: Partial<LicenseTemplateConfig>): void
Updates the configuration.
Supported File Types
The license manager supports a wide range of file types with appropriate license formats:
C-Style Comments (/* */)
- JavaScript (.js, .jsx)
- TypeScript (.ts, .tsx)
- CSS (.css)
- SQL (.sql)
- Shell scripts (.sh, .bash)
- C/C++ (.c, .cpp, .h, .hpp)
- Java (.java)
- PHP (.php)
- Ruby (.rb)
- Go (.go)
- Rust (.rs)
- Swift (.swift)
- Kotlin (.kt)
- Scala (.scala)
- And many more...
Python Docstrings (""")
- Python (.py)
HTML Comments ()
- HTML (.html)
No License Required
- Log files (.log)
- Lock files (.lock)
- Source maps (.map)
Configuration
LicenseTemplateConfig
interface LicenseTemplateConfig {
templates: Record<string, LicenseTemplate>;
defaultTemplate: string;
fileTypeMapping: Record<FileType, string>;
excludePatterns: string[];
includePatterns: string[];
}Custom Configuration Example
const customConfig: Partial<LicenseTemplateConfig> = {
templates: {
'mit': {
text: 'MIT License\nCopyright (c) 2025 Your Company',
format: 'c-style',
startDelimiter: '/*',
endDelimiter: '*/'
}
},
fileTypeMapping: {
'js': 'mit',
'ts': 'mit'
},
excludePatterns: [
'node_modules/**',
'dist/**',
'build/**'
]
};
const licenseManager = new LicenseManager(customConfig);License Header Options
LicenseHeaderOptions
interface LicenseHeaderOptions {
copyrightYear?: number;
companyName?: string;
licenseType?: 'limited-use' | 'mit' | 'apache' | 'gpl' | 'custom';
customText?: string;
skipFiles?: string[];
includeFiles?: string[];
dryRun?: boolean;
}Options Example
const options: LicenseHeaderOptions = {
copyrightYear: 2024,
companyName: 'My Company',
dryRun: true, // Preview changes
skipFiles: ['generated.js', 'vendor/**']
};
licenseManager.addLicenseHeader('src/file.js', options);Examples
Add License to Single File
import { LicenseManager } from '@bernierllc/license-manager';
const licenseManager = new LicenseManager();
// Add license header
const success = licenseManager.addLicenseHeader('src/my-component.tsx');
if (success) {
console.log('License header added successfully');
} else {
console.log('Failed to add license header');
}Validate License Compliance
const validation = licenseManager.validateLicenseHeader('src/file.js');
if (!validation.hasLicense) {
console.log('❌ No license header found');
console.log('Expected:', validation.expectedText);
} else if (!validation.isValid) {
console.log('⚠️ Invalid license header');
validation.errors.forEach(error => console.log(` - ${error}`));
} else {
console.log('✅ Valid license header');
}Scan Project for Compliance
const scanResult = licenseManager.scanDirectory('./src');
console.log(`📊 License Compliance Report`);
console.log(`Total files: ${scanResult.totalFiles}`);
console.log(`Files with license: ${scanResult.filesWithLicense}`);
console.log(`Files without license: ${scanResult.filesWithoutLicense}`);
console.log(`Compliance rate: ${scanResult.complianceRate.toFixed(1)}%`);
if (scanResult.summary.missing.length > 0) {
console.log('\n❌ Files missing license:');
scanResult.summary.missing.forEach(file => console.log(` - ${file}`));
}
if (scanResult.summary.invalid.length > 0) {
console.log('\n⚠️ Files with invalid license:');
scanResult.summary.invalid.forEach(file => console.log(` - ${file}`));
}Batch Add Licenses
const files = [
'src/components/Button.tsx',
'src/utils/helpers.ts',
'src/styles/main.css'
];
files.forEach(file => {
const success = licenseManager.addLicenseHeader(file, { dryRun: false });
console.log(`${file}: ${success ? '✅' : '❌'}`);
});Custom License Template
const customManager = new LicenseManager({
templates: {
'custom': {
text: `/*
Copyright (c) 2025 Custom Company
This software is proprietary and confidential.
Unauthorized copying is prohibited.
*/`,
format: 'c-style',
startDelimiter: '/*',
endDelimiter: '*/'
}
},
fileTypeMapping: {
'js': 'custom',
'ts': 'custom'
}
});Testing
The package includes comprehensive tests with mocked file system:
npm testTest Coverage
- File type detection
- License template generation
- License validation
- File operations (read/write)
- Directory scanning
- Configuration management
- Error handling
Error Handling
The license manager provides detailed error information:
const validation = licenseManager.validateLicenseHeader('src/file.js');
if (validation.errors.length > 0) {
console.log('Validation errors:');
validation.errors.forEach(error => console.log(` - ${error}`));
}
if (validation.warnings.length > 0) {
console.log('Validation warnings:');
validation.warnings.forEach(warning => console.log(` - ${warning}`));
}Best Practices
- Use Dry Run First: Always test with
dryRun: truebefore making changes - Exclude Generated Files: Configure exclude patterns for build outputs
- Customize for Your Project: Update company name and copyright year
- Regular Compliance Checks: Scan your project regularly for license compliance
- Handle Errors Gracefully: Check return values and handle file system errors
Contributing
This package is part of the Bernier LLC tools ecosystem. Please follow the project's contribution guidelines.
License
This package is licensed under the same terms as the project it's delivered for. See the license header in source files for details.
