@rbleattler/omp-ts-typegen 0.2025.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,192 @@
1
+ # Understanding Oh My Posh Schema.json
2
+
3
+ This document explains the structure and purpose of the Oh My Posh `schema.json` file, which defines the configuration format for Oh My Posh themes.
4
+
5
+ ## Overview
6
+
7
+ Oh My Posh uses a JSON schema (following the JSON Schema Draft-07 specification) to:
8
+
9
+ 1. Validate theme configuration files
10
+ 2. Provide auto-completion in editors with JSON schema support
11
+ 3. Define the structure of themes in a standardized way
12
+ 4. Document available options for theme creators
13
+
14
+ ## Schema Structure
15
+
16
+ ### Root Schema Properties
17
+
18
+ The schema's root properties define the high-level configuration options:
19
+
20
+ - **`final_space`**: Whether to add a space at the end of the prompt
21
+ - **`enable_cursor_positioning`**: Enables precise cursor positioning features
22
+ - **`shell_integration`**: Adds FTCS command marks for shell integration
23
+ - **`pwd`**: Controls OSC99/7/51 working directory communication
24
+ - **`upgrade`**: Configuration for upgrade notifications
25
+ - **`patch_pwsh_bleed`**: Fixes PowerShell color bleeding issues
26
+ - **`console_title_template`**: Template for the terminal window title
27
+ - **`terminal_background`**: Background color of the terminal
28
+ - **`blocks`**: The main array of prompt blocks (core structure of the prompt)
29
+ - **`tooltips`**: Custom tooltips for specific commands
30
+ - **`transient_prompt`**: Configuration for simplified repeated prompts
31
+ - **`valid_line`**, **`error_line`**: PowerShell-specific prompt variants
32
+ - **`secondary_prompt`**: Configuration for multi-line input continuation
33
+ - **`debug_prompt`**: PowerShell debugging prompt configuration
34
+ - **`palette`**, **`palettes`**: Color palette definitions
35
+ - **`cycle`**: Color cycling configuration
36
+ - **`accent_color`**: Theme accent color
37
+ - **`var`**: Custom variables for use in templates
38
+
39
+ ### Definitions Section
40
+
41
+ The `definitions` section contains reusable schema components:
42
+
43
+ #### Color Definitions
44
+
45
+ ```json
46
+ "color": {
47
+ "anyOf": [
48
+ {
49
+ "$ref": "#/definitions/color_string"
50
+ },
51
+ {
52
+ "$ref": "#/definitions/palette_reference"
53
+ }
54
+ ]
55
+ }
56
+ ```
57
+
58
+ Colors can be specified as direct color strings or as palette references (e.g., `p:blue`).
59
+
60
+ #### Block Definition
61
+
62
+ Blocks are the main structural elements of the prompt:
63
+
64
+ ```json
65
+ "block": {
66
+ "type": "object",
67
+ "description": "https://ohmyposh.dev/docs/configuration/block",
68
+ "properties": {
69
+ "type": {
70
+ "type": "string",
71
+ "enum": ["prompt", "rprompt"],
72
+ "default": "prompt"
73
+ },
74
+ "alignment": {
75
+ "type": "string",
76
+ "enum": ["left", "right"],
77
+ "default": "left"
78
+ },
79
+ "segments": {
80
+ "type": "array",
81
+ "items": {
82
+ "$ref": "#/definitions/segment"
83
+ }
84
+ },
85
+ // ...other properties
86
+ }
87
+ }
88
+ ```
89
+
90
+ #### Segment Definition
91
+
92
+ Segments are the individual components within blocks that display information:
93
+
94
+ ```json
95
+ "segment": {
96
+ "type": "object",
97
+ "required": ["type", "style"],
98
+ "properties": {
99
+ "type": {
100
+ "type": "string",
101
+ "enum": ["git", "node", "python", /* many other segment types */]
102
+ },
103
+ "style": {
104
+ "anyOf": [
105
+ {
106
+ "enum": ["plain", "powerline", "diamond", "accordion"]
107
+ },
108
+ {
109
+ "type": "string"
110
+ }
111
+ ]
112
+ },
113
+ // ...many other properties
114
+ }
115
+ }
116
+ ```
117
+
118
+ The schema then uses conditional validation (`if`/`then`) to define specific properties for each segment type.
119
+
120
+ ## Segment Types
121
+
122
+ Oh My Posh includes a wide variety of segment types, each with specific functionality:
123
+
124
+ ### SCM Segments
125
+
126
+ - **`git`**: Git repository information
127
+ - **`mercurial`**: Mercurial repository information
128
+ - **`fossil`**: Fossil repository information
129
+ - **`sapling`**: Sapling repository information
130
+ - **`plastic`**: Plastic SCM information
131
+ - **`svn`**: SVN repository information
132
+
133
+ ### Language/Runtime Segments
134
+
135
+ - **`node`**: Node.js version and environment
136
+ - **`python`**: Python version and virtual environment
137
+ - **`ruby`**: Ruby version
138
+ - **`java`**: Java version
139
+ - **`go`**: Go version
140
+ - **`rust`**: Rust version
141
+ - **`dotnet`**: .NET version
142
+ - **`php`**: PHP version
143
+ - And many more language-specific segments
144
+
145
+ ### Cloud/Service Segments
146
+
147
+ - **`aws`**: AWS profile and region
148
+ - **`az`**: Azure information
149
+ - **`gcp`**: Google Cloud Platform information
150
+ - **`kubernetes`**: Kubernetes context
151
+
152
+ ### System Segments
153
+
154
+ - **`os`**: Operating system information
155
+ - **`path`**: Current directory path
156
+ - **`time`**: Current time
157
+ - **`session`**: SSH session indicator
158
+ - **`battery`**: Battery status
159
+
160
+ ### CLI Tool Segments
161
+
162
+ - **`npm`**: NPM information
163
+ - **`yarn`**: Yarn information
164
+ - **`pnpm`**: PNPM information
165
+ - **`terraform`**: Terraform workspace
166
+
167
+ ## How Validation Works
168
+
169
+ The schema uses several validation techniques:
170
+
171
+ 1. **Required properties**: Ensures essential properties are present
172
+ 2. **Enum validation**: Restricts values to specific options
173
+ 3. **Pattern validation**: Validates string format (like colors)
174
+ 4. **Conditional validation**: Different validation rules based on segment type
175
+ 5. **Default values**: Provides sensible defaults where applicable
176
+
177
+ ## Example Configuration Flow
178
+
179
+ When a user creates an Oh My Posh theme:
180
+
181
+ 1. The theme defines one or more blocks
182
+ 2. Each block contains one or more segments
183
+ 3. Each segment has a type, style, and segment-specific properties
184
+ 4. Colors can be defined directly or through palettes
185
+ 5. Templates within segments define how information is displayed
186
+
187
+ ## References
188
+
189
+ - [Oh My Posh Documentation](https://ohmyposh.dev/docs)
190
+ - [JSON Schema Specification](https://json-schema.org/specification.html)
191
+
192
+ This schema enables the rich, customizable prompts that Oh My Posh is known for, while providing clear validation and documentation for theme creators.
@@ -0,0 +1,184 @@
1
+ import fs from 'fs/promises';
2
+ import path from 'path';
3
+ import axios from 'axios';
4
+ import {
5
+ quicktype,
6
+ InputData,
7
+ jsonInputForTargetLanguage,
8
+ JSONSchemaInput,
9
+ FetchingJSONSchemaStore
10
+ } from "quicktype-core";
11
+
12
+ const SCHEMA_URL = 'https://raw.githubusercontent.com/JanDeDobbeleer/oh-my-posh/refs/heads/main/themes/schema.json';
13
+ const OUTPUT_DIR = path.join(process.cwd(), 'src', 'types');
14
+ const OUTPUT_FILE = path.join(OUTPUT_DIR, 'omp.ts');
15
+ const SCHEMA_CACHE_FILE = path.join(process.cwd(), 'cache', 'schema.json');
16
+
17
+ async function main() {
18
+ // Dynamically import chalk (ESM module)
19
+ const { default: chalk } = await import('chalk');
20
+
21
+ console.log(chalk.blue('Starting TypeScript type generation...'));
22
+
23
+ try {
24
+ // Ensure output directories exist
25
+ await fs.mkdir(path.join(process.cwd(), 'cache'), { recursive: true });
26
+ await fs.mkdir(OUTPUT_DIR, { recursive: true });
27
+
28
+ // Fetch the latest schema from the Oh My Posh repository
29
+ console.log(chalk.yellow('Fetching schema from Oh My Posh repository...'));
30
+ const response = await axios.get(SCHEMA_URL);
31
+ const schema = response.data;
32
+
33
+ // This is a dumb workaround but maybe someday I can get the schema file to not have this title...
34
+ // Remove the title property from definitions.segment to avoid dumb naming
35
+ //TODO: Create an issue on the Oh My Posh repository to remove the title property from the segment definition in the schema file... or fix it myself with a PR
36
+ // PR pending: [fix: update segment title in schema.json #6244](https://github.com/JanDeDobbeleer/oh-my-posh/pull/6244)
37
+ if (schema.definitions && schema.definitions.segment) {
38
+ delete schema.definitions.segment.title;
39
+ }
40
+
41
+ // Cache the schema for future comparisons
42
+ await fs.writeFile(SCHEMA_CACHE_FILE, JSON.stringify(schema, null, 2), { flag: 'w' });
43
+
44
+
45
+ console.log(chalk.green('Schema fetched and cached successfully.'));
46
+
47
+ // Generate TypeScript types using quicktype with the provided options
48
+ console.log(chalk.yellow('Generating TypeScript types...'));
49
+
50
+
51
+
52
+ // Set up quicktype options based on the available options in quicktype-core
53
+ const quicktypeOptions = {
54
+ // if debug add debugPrintGraph: true
55
+ // This will print the type graph to the console at every processing step
56
+ debugPrintGraph: process.features.debug ? true : false,
57
+
58
+ // Check Provenance:
59
+ // Check that we're propagating all type attributes (unless we actually can't)
60
+ //! Experimenting with this
61
+ checkProvenance: true,
62
+
63
+ inferMaps: true,
64
+ inferEnums: true,
65
+ inferDateTimes: true,
66
+ inferIntegerStrings: true,
67
+ inferBooleanStrings: true,
68
+ inferUUIDStrings: true, // Renamed from inferUuids to match quicktype's API
69
+ combineClasses: true,
70
+ allPropertiesOptional: false,
71
+ alphabetizeProperties: true, // Sort properties for better readability
72
+ rendererOptions: {
73
+ "explicit-unions": true,
74
+ "runtime-typecheck": true,
75
+ "acronym-style": "original",
76
+ "converters": "top-level",
77
+ "raw-type": "json",
78
+ "prefer-unions": true,
79
+ "prefer-types": true
80
+ },
81
+ // Additional options from Options interface
82
+ fixedTopLevels: true,
83
+ leadingComments: undefined,
84
+ density: "normal" as const, // Available options: 'normal', 'dense'
85
+ useStructuralFeatures: true
86
+ };
87
+
88
+ // Generate the types using quicktype API
89
+ const { lines } = await quicktypeJSONSchema("typescript", "OhMyPosh", JSON.stringify(schema), quicktypeOptions);
90
+
91
+ // Add a header to the generated file
92
+ const header = `/**
93
+ * Oh My Posh TypeScript definitions
94
+ *
95
+ * Generated from schema: ${SCHEMA_URL}
96
+ * Generated on: ${new Date().toISOString()}
97
+ *
98
+ * @see https://ohmyposh.dev/docs/
99
+ */
100
+
101
+ /* eslint-disable */
102
+ /* tslint:disable */
103
+
104
+ `;
105
+
106
+ let typesContent = header + lines.join('\n');
107
+
108
+ // Ensure the OhMyPosh type is properly exported
109
+ // This adds an export statement if one isn't already present
110
+ if (!typesContent.includes('export interface OhMyPosh')) {
111
+ typesContent = typesContent.replace(
112
+ 'interface OhMyPosh',
113
+ 'export interface OhMyPosh'
114
+ );
115
+ }
116
+
117
+ // Write the generated TypeScript types to the output file
118
+ await fs.writeFile(OUTPUT_FILE, typesContent, { flag: 'w' });
119
+ console.log(chalk.green(`TypeScript types generated successfully at ${OUTPUT_FILE}`));
120
+
121
+ } catch (error) {
122
+ // Dynamically import chalk again to ensure it's available in the catch block
123
+ const { default: chalk } = await import('chalk');
124
+ console.error(chalk.red('Error generating TypeScript types:'), error);
125
+ process.exit(1);
126
+ }
127
+ }
128
+
129
+
130
+ // This function is not currently used. But it can be used to generate types from JSON input.
131
+ // We'll keep it here for reference / future use.
132
+ async function quicktypeJSON(
133
+ targetLanguage: string,
134
+ typeName: string,
135
+ jsonString: string
136
+ ) {
137
+ const jsonInput = jsonInputForTargetLanguage(targetLanguage);
138
+
139
+ // We could add multiple samples for the same desired
140
+ // type, or many sources for other types. Here we're
141
+ // just making one type from one piece of sample JSON.
142
+ await jsonInput.addSource({
143
+ name: typeName,
144
+ samples: [jsonString]
145
+ });
146
+
147
+ const inputData = new InputData();
148
+ inputData.addInput(jsonInput);
149
+
150
+ return await quicktype({
151
+ inputData,
152
+ lang: targetLanguage
153
+ });
154
+ }
155
+
156
+ async function quicktypeJSONSchema(
157
+ targetLanguage: string,
158
+ typeName: string,
159
+ jsonSchemaString: string,
160
+ options: any = {}
161
+ ) {
162
+ const schemaInput = new JSONSchemaInput(new FetchingJSONSchemaStore());
163
+
164
+ // We could add multiple schemas for multiple types,
165
+ // but here we're just making one type from JSON schema.
166
+ await schemaInput.addSource({ name: typeName, schema: jsonSchemaString });
167
+
168
+ const inputData = new InputData();
169
+ inputData.addInput(schemaInput);
170
+
171
+ // Pass all options to quicktype along with the required inputData and lang
172
+ return await quicktype({
173
+ ...options,
174
+ inputData,
175
+ lang: targetLanguage
176
+ });
177
+ }
178
+
179
+ main().catch(async error => {
180
+ // Dynamically import chalk in catch block
181
+ const { default: chalk } = await import('chalk');
182
+ console.error(chalk.red('Unhandled error:'), error);
183
+ process.exit(1);
184
+ });