Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[php2cpg] Try multiple charsets when reading file content #5222

Merged
merged 3 commits into from
Jan 14, 2025
Merged
Changes from 1 commit
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
Next Next commit
[php2cpg] Try multiple charsets when reading file content
johannescoetzee committed Jan 13, 2025
commit f76033c8d2a3d7b093a6e234b294749b875ba447
Original file line number Diff line number Diff line change
@@ -19,6 +19,7 @@ import org.slf4j.LoggerFactory
import java.nio.charset.StandardCharsets
import java.nio.file.{Files, Path}
import scala.collection.mutable
import scala.util.{Success, Try}

class AstCreator(relativeFileName: String, fileName: String, phpAst: PhpFile, disableFileContent: Boolean)(implicit
withSchemaValidation: ValidationMode
@@ -29,13 +30,33 @@ class AstCreator(relativeFileName: String, fileName: String, phpAst: PhpFile, di
private val scope = new Scope()(() => nextClosureName())
private val tmpKeyPool = new IntervalKeyPool(first = 0, last = Long.MaxValue)
private val globalNamespace = globalNamespaceBlock()
private var fileContent = Option.empty[String]
private val fileEncodings = List(
StandardCharsets.UTF_8,
StandardCharsets.UTF_16,
StandardCharsets.ISO_8859_1,
StandardCharsets.US_ASCII,
StandardCharsets.UTF_16LE,
StandardCharsets.UTF_16BE
)
private var fileContent = Option.empty[String]

private def getNewTmpName(prefix: String = "tmp"): String = s"$prefix${tmpKeyPool.next.toString}"

override def createAst(): DiffGraphBuilder = {
if (!disableFileContent) {
fileContent = Some(Files.readString(Path.of(fileName)))

fileContent = fileEncodings.iterator
.map { encoding =>
Try(Files.readString(Path.of(fileName), encoding))
}
.collectFirst { case Success(content) =>
content
}

if (fileContent.isEmpty) {
logger.warn(s"Could not parse file using any standard charsets. File content will be missing for $fileName")
}
}

val ast = astForPhpFile(phpAst)