Skip to content

Commit

Permalink
use simpler hcl2-json for parsing tf files
Browse files Browse the repository at this point in the history
  • Loading branch information
pulasthibandara committed Aug 13, 2024
1 parent 6cd3739 commit 75b1f38
Show file tree
Hide file tree
Showing 5 changed files with 236 additions and 38 deletions.
2 changes: 1 addition & 1 deletion packages/terraform/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,6 @@
"builders": "./executors.json",
"generators": "./generators.json",
"dependencies": {
"@evops/hcl-terraform-parser": "^1.0.0"
"hcl2-json-parser": "^1.0.1"
}
}
20 changes: 15 additions & 5 deletions packages/terraform/src/graph.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import * as hclParser from '@evops/hcl-terraform-parser'
import {
CreateDependencies,
logger,
RawProjectGraphDependency,
workspaceRoot
} from '@nx/devkit'
import * as hcl2JsonParser from 'hcl2-json-parser'
import * as fs from 'node:fs/promises'
import * as path from 'node:path'
import { DependencyType } from 'nx/src/config/project-graph'
Expand All @@ -27,11 +28,20 @@ export const createDependencies: CreateDependencies = async (_, ctx) => {

for (const file of tfFilesToProcess) {
const data = await fs.readFile(file.file)
const hclFile = hclParser.parse(data)
const moduleCalls = hclFile['module_calls']

for (const moduleCall of Object.values(moduleCalls)) {
const depSourcePathRel = moduleCall.source
let parsed: hcl2JsonParser.HclDef

try {
parsed = await hcl2JsonParser.parseToObject(data.toString())
} catch (e) {
logger.warn(
`Failed to parse .tf file ${file.file}. Error: ${e.message}`
)
continue
}

for (const moduleCall of Object.values(parsed.module ?? [])) {
const depSourcePathRel = moduleCall[0]?.source

if (!isLocalPath(depSourcePathRel)) {
continue
Expand Down
11 changes: 0 additions & 11 deletions packages/terraform/src/hcl-terraform-parser.d.ts

This file was deleted.

27 changes: 27 additions & 0 deletions packages/terraform/src/hcl2-json-parser.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
declare module 'hcl2-json-parser' {
export type HclDef = {
data?: {
[data: string]: {
[dataName: string]: [{ [propertyName: string]: any }]
}
}

resource?: {
[resource: string]: {
[resourceName: string]: [{ [propertyName: string]: any }]
}
}

terraform?: [
{
backend?: [{ [propertyName: string]: any }]
}
]

module?: {
[moduleName: string]: [{ source: string }]
}
}

export function parseToObject(data: string): Promise<HclDef>
}
Loading

0 comments on commit 75b1f38

Please sign in to comment.