用php写了一个统计Lua脚本行数的工具

2024-04-19 15:32
文章标签 工具 统计 php 脚本 lua 行数

本文主要是介绍用php写了一个统计Lua脚本行数的工具,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

在quick-cocos2d-x的打包编译Lua的php文件里面加入统计Lua脚本行数的功能

关键代码就这么一行,在windows上面用find函数

list($line,$file,$size) = explode(" ",shell_exec("find /V \"\" /C ".$path));

在linux上面直接由wc 函数可以返回文本行数的貌似。。替换一下就可以了。

<?php
define('DS', DIRECTORY_SEPARATOR);
define('LUAJIT', false);
class LuaPackager
{
private $packageName    = '';
private $rootdir        = '';
private $rootdirLength  = 0;
private $files          = array();
private $modules        = array();
private $excludes       = array();
private $totalLine 		= 0;
function __construct($config)
{
$this->rootdir       = realpath($config['srcdir']);
$this->rootdirLength = strlen($this->rootdir) + 1;
$this->packageName   = trim($config['packageName'], '.');
$this->excludes      = $config['excludes'];
$this->totalLine     = 0;
if (!empty($this->packageName))
{
$this->packageName = $this->packageName . '.';
}
}
function dumpZip($outputFileBasename)
{
$this->files = array();
$this->modules = array();
print("compile script files\n");
$this->compile();
if (empty($this->files))
{
printf("error.\nERROR: not found script files in %s\n", $this->rootdir);
return;
}
$zipFilename = $outputFileBasename . '.zip';
$zip = new ZipArchive();
if ($zip->open($zipFilename, ZIPARCHIVE::OVERWRITE | ZIPARCHIVE::CM_STORE))
{
printf("create ZIP bundle file: %s\n", $zipFilename);
foreach ($this->modules as $module)
{
$zip->addFromString($module['moduleName'], $module['bytes']);
}
$zip->close();
printf("done.\n\n");
}
printf("\n============================================: %d Lines  ",$this->totalLine);
print <<<EOT
### HOW TO USE ###
1. Add code to your lua script:
CCLuaLoadChunksFromZip("${zipFilename}")
EOT;
}
function dump($outputFileBasename)
{
$this->files = array();
$this->modules = array();
print("compile script files\n");
$this->compile();
if (empty($this->files))
{
printf("error.\nERROR: not found script files in %s\n", $this->rootdir);
return;
}
$headerFilename = $outputFileBasename . '.h';
printf("create C header file: %s\n", $headerFilename);
file_put_contents($headerFilename, $this->renderHeaderFile($outputFileBasename));
$sourceFilename = $outputFileBasename . '.c';
printf("create C source file: %s\n", $sourceFilename);
file_put_contents($sourceFilename, $this->renderSourceFile($outputFileBasename));
printf("\n============================================: %d Lines  ",$this->totalLine);
printf("done.\n\n");
$outputFileBasename = basename($outputFileBasename);
print <<<EOT
### HOW TO USE ###
1. Add code to AppDelegate.cpp:
extern "C" {
#include "${outputFileBasename}.h"
}
2. Add code to AppDelegate::applicationDidFinishLaunching()
CCScriptEngineProtocol* pEngine = CCScriptEngineManager::sharedManager()->getScriptEngine();
luaopen_${outputFileBasename}(pEngine->getLuaState());
pEngine->executeString("require(\"main\")");
EOT;
}
private function compile()
{
if (file_exists($this->rootdir) && is_dir($this->rootdir))
{
$this->files = $this->getFiles($this->rootdir);
}
foreach ($this->files as $path)
{
$filename = substr($path, $this->rootdirLength);
$fi = pathinfo($filename);
if ($fi['extension'] != 'lua') continue;
$basename = ltrim($fi['dirname'] . DS . $fi['filename'], '/\\.');
$moduleName = $this->packageName . str_replace(DS, '.', $basename);
$found = false;
foreach ($this->excludes as $k => $v)
{
if (substr($moduleName, 0, strlen($v)) == $v)
{
$found = true;
break;
}
}
if ($found) continue;
printf('  compile module: %s...', $moduleName);
$bytes = $this->compileFile($path);
if ($bytes == false)
{
print("error.\n");
}
else
{
print("ok.\n");
$bytesName = 'lua_m_' . strtolower(str_replace('.', '_', $moduleName));
$this->modules[] = array(
'moduleName'    => $moduleName,
'bytesName'     => $bytesName,
'functionName'  => 'luaopen_' . $bytesName,
'basename'      => $basename,
'bytes'         => $bytes,
);
}
}
}
private function getFiles($dir)
{
$files = array();
$dir = rtrim($dir, "/\\") . DS;
$dh = opendir($dir);
if ($dh == false) { return $files; }
while (($file = readdir($dh)) !== false)
{
if ($file{0} == '.') { continue; }
$path = $dir . $file;
if (is_dir($path))
{
$files = array_merge($files, $this->getFiles($path));
}
elseif (is_file($path))
{
$files[] = $path;
}
}
closedir($dh);
return $files;
}
private function getFileLine($path)
{
$size = 0;
if (file_exists($path))
{	
list($line,$file,$size) = explode(" ",shell_exec("find /V \"\" /C ".$path));
}
return $size;
}
private function compileFile($path)
{
$line = $this->getFileLine($path);
$this->totalLine = $this->totalLine + $line;
printf("\n============================================: %d Lines  ",$this->totalLine);
$tmpfile = $path . '.bytes';
if (file_exists($tmpfile)) unlink($tmpfile);
if (LUAJIT)
{
$command = sprintf('luajit -b -s "%s" "%s"', $path, $tmpfile);
}
else
{
$command = sprintf('luac -o "%s" "%s"', $tmpfile, $path);
}
passthru($command);
if (!file_exists($tmpfile)) return false;
$bytes = file_get_contents($tmpfile);
unlink($tmpfile);
return $bytes;
}
private function renderHeaderFile($outputFileBasename)
{
$headerSign = '__LUA_MODULES_' . strtoupper(md5(time())) . '_H_';
$outputFileBasename = basename($outputFileBasename);
$contents = array();
$contents[] = <<<EOT
/* ${outputFileBasename}.h */
#ifndef ${headerSign}
#define ${headerSign}
#if __cplusplus
extern "C" {
#endif
#include "lua.h"
void luaopen_${outputFileBasename}(lua_State* L);
#if __cplusplus
}
#endif
EOT;
$contents[] = '/*';
foreach ($this->modules as $module)
{
// $contents[] = sprintf('/* %s, %s.lua */', $module['moduleName'], $module['basename']);
$contents[] = sprintf('int %s(lua_State* L);', $module['functionName']);
}
$contents[] = '*/';
$contents[] = <<<EOT
#endif /* ${headerSign} */
EOT;
return implode("\n", $contents);
}
private function renderSourceFile($outputFileBasename)
{
$outputFileBasename = basename($outputFileBasename);
$contents = array();
$contents[] = <<<EOT
/* ${outputFileBasename}.c */
#include "lua.h"
#include "lauxlib.h"
#include "${outputFileBasename}.h"
EOT;
foreach ($this->modules as $module)
{
$contents[] = sprintf('/* %s, %s.lua */', $module['moduleName'], $module['basename']);
$contents[] = sprintf('static const unsigned char %s[] = {', $module['bytesName']);
// $contents[] = $this->encodeBytes($module['bytes']);
$contents[] = $this->encodeBytesFast($module['bytes']);
$contents[] = '};';
$contents[] = '';
}
$contents[] = '';
foreach ($this->modules as $module)
{
$functionName = $module['functionName'];
$bytesName    = $module['bytesName'];
$basename     = $module['basename'];
$contents[] = <<<EOT
int ${functionName}(lua_State *L) {
int arg = lua_gettop(L);
luaL_loadbuffer(L,
(const char*)${bytesName},
sizeof(${bytesName}),
"${basename}.lua");
lua_insert(L,1);
lua_call(L,arg,1);
return 1;
}
EOT;
}
$contents[] = '';
$contents[] = "static luaL_Reg ${outputFileBasename}_modules[] = {";
foreach ($this->modules as $module)
{
$contents[] = sprintf('    {"%s", %s},',
$module["moduleName"],
$module["functionName"]);
}
$contents[] = <<<EOT
{NULL, NULL}
};
void luaopen_${outputFileBasename}(lua_State* L)
{
luaL_Reg* lib = ${outputFileBasename}_modules;
for (; lib->func; lib++)
{
lua_getglobal(L, "package");
lua_getfield(L, -1, "preload");
lua_pushcfunction(L, lib->func);
lua_setfield(L, -2, lib->name);
lua_pop(L, 2);
}
}
EOT;
return implode("\n", $contents);
}
private function encodeBytes($bytes)
{
$len      = strlen($bytes);
$contents = array();
$offset   = 0;
$buffer   = array();
while ($offset < $len)
{
$buffer[] = ord(substr($bytes, $offset, 1));
if (count($buffer) == 16)
{
$contents[] = $this->encodeBytesBlock($buffer);
$buffer = array();
}
$offset++;
}
if (!empty($buffer))
{
$contents[] = $this->encodeBytesBlock($buffer);
}
return implode("\n", $contents);
}
private function encodeBytesFast($bytes)
{
$len = strlen($bytes);
$output = array();
for ($i = 0; $i < $len; $i++)
{
$output[] = sprintf('%d,', ord($bytes{$i}));
}
return implode('', $output);
}
private function encodeBytesBlock($buffer)
{
$output = array();
$len = count($buffer);
for ($i = 0; $i < $len; $i++)
{
$output[] = sprintf('%d,', $buffer[$i]);
}
return implode('', $output);
}
}
function help()
{
echo <<<EOT
usage: php package_scripts.php [options] dirname output_filename
options:
--bundle make bundle file
-p prefix package name
-x exclude packages, eg: -x framework.server, framework.tests
EOT;
}
if ($argc < 3)
{
help();
exit(1);
}
array_shift($argv);
$config = array(
'packageName'        => '',
'excludes'           => array(),
'srcdir'             => '',
'outputFileBasename' => '',
'zip'                => false,
);
do
{
if ($argv[0] == '-p')
{
$config['packageName'] = $argv[1];
array_shift($argv);
}
else if ($argv[0] == '-x')
{
$excludes = explode(',', $argv[1]);
foreach ($excludes as $k => $v)
{
$v = trim($v);
if (empty($v))
{
unset($excludes[$k]);
}
else
{
$excludes[$k] = $v;
}
}
$config['excludes'] = $excludes;
array_shift($argv);
}
else if ($argv[0] == '-zip')
{
$config['zip'] = true;
}
else if ($config['srcdir'] == '')
{
$config['srcdir'] = $argv[0];
}
else
{
$config['outputFileBasename'] = $argv[0];
}
array_shift($argv);
} while (count($argv) > 0);
$packager = new LuaPackager($config);
if ($config['zip'])
{
$packager->dumpZip($config['outputFileBasename']);
}
else
{
$packager->dump($config['outputFileBasename']);
}


 

这篇关于用php写了一个统计Lua脚本行数的工具的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/917937

相关文章

Linux中压缩、网络传输与系统监控工具的使用完整指南

《Linux中压缩、网络传输与系统监控工具的使用完整指南》在Linux系统管理中,压缩与传输工具是数据备份和远程协作的桥梁,而系统监控工具则是保障服务器稳定运行的眼睛,下面小编就来和大家详细介绍一下它... 目录引言一、压缩与解压:数据存储与传输的优化核心1. zip/unzip:通用压缩格式的便捷操作2.

sqlite3 命令行工具使用指南

《sqlite3命令行工具使用指南》本文系统介绍sqlite3CLI的启动、数据库操作、元数据查询、数据导入导出及输出格式化命令,涵盖文件管理、备份恢复、性能统计等实用功能,并说明命令分类、SQL语... 目录一、启动与退出二、数据库与文件操作三、元数据查询四、数据操作与导入导出五、查询输出格式化六、实用功

在Linux终端中统计非二进制文件行数的实现方法

《在Linux终端中统计非二进制文件行数的实现方法》在Linux系统中,有时需要统计非二进制文件(如CSV、TXT文件)的行数,而不希望手动打开文件进行查看,例如,在处理大型日志文件、数据文件时,了解... 目录在linux终端中统计非二进制文件的行数技术背景实现步骤1. 使用wc命令2. 使用grep命令

利用Python脚本实现批量将图片转换为WebP格式

《利用Python脚本实现批量将图片转换为WebP格式》Python语言的简洁语法和库支持使其成为图像处理的理想选择,本文将介绍如何利用Python实现批量将图片转换为WebP格式的脚本,WebP作为... 目录简介1. python在图像处理中的应用2. WebP格式的原理和优势2.1 WebP格式与传统

基于Python开发Windows屏幕控制工具

《基于Python开发Windows屏幕控制工具》在数字化办公时代,屏幕管理已成为提升工作效率和保护眼睛健康的重要环节,本文将分享一个基于Python和PySide6开发的Windows屏幕控制工具,... 目录概述功能亮点界面展示实现步骤详解1. 环境准备2. 亮度控制模块3. 息屏功能实现4. 息屏时间

SQLite3命令行工具最佳实践指南

《SQLite3命令行工具最佳实践指南》SQLite3是轻量级嵌入式数据库,无需服务器支持,具备ACID事务与跨平台特性,适用于小型项目和学习,sqlite3.exe作为命令行工具,支持SQL执行、数... 目录1. SQLite3简介和特点2. sqlite3.exe使用概述2.1 sqlite3.exe

Linux脚本(shell)的使用方式

《Linux脚本(shell)的使用方式》:本文主要介绍Linux脚本(shell)的使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录概述语法详解数学运算表达式Shell变量变量分类环境变量Shell内部变量自定义变量:定义、赋值自定义变量:引用、修改、删

基于Python实现一个Windows Tree命令工具

《基于Python实现一个WindowsTree命令工具》今天想要在Windows平台的CMD命令终端窗口中使用像Linux下的tree命令,打印一下目录结构层级树,然而还真有tree命令,但是发现... 目录引言实现代码使用说明可用选项示例用法功能特点添加到环境变量方法一:创建批处理文件并添加到PATH1

使用jenv工具管理多个JDK版本的方法步骤

《使用jenv工具管理多个JDK版本的方法步骤》jenv是一个开源的Java环境管理工具,旨在帮助开发者在同一台机器上轻松管理和切换多个Java版本,:本文主要介绍使用jenv工具管理多个JD... 目录一、jenv到底是干啥的?二、jenv的核心功能(一)管理多个Java版本(二)支持插件扩展(三)环境隔

Python使用smtplib库开发一个邮件自动发送工具

《Python使用smtplib库开发一个邮件自动发送工具》在现代软件开发中,自动化邮件发送是一个非常实用的功能,无论是系统通知、营销邮件、还是日常工作报告,Python的smtplib库都能帮助我们... 目录代码实现与知识点解析1. 导入必要的库2. 配置邮件服务器参数3. 创建邮件发送类4. 实现邮件