72 lines
2.2 KiB
C
72 lines
2.2 KiB
C
/*
|
||
* pack.c — 独立的前端文件打包工具(不依赖 mongoose)
|
||
*
|
||
* 编译: gcc -o pack pack.c
|
||
* 用法: ./pack [-s strip_prefix] file1 file2 ... > packed_fs.c
|
||
*
|
||
* 生成的 C 文件包含:
|
||
* - struct mg_mem_file 定义
|
||
* - 每个文件的字节数组
|
||
* - mg_packed_files[] 索引表
|
||
* - mg_unpack() / mg_unlist() 实现
|
||
*/
|
||
#include <errno.h>
|
||
#include <stdio.h>
|
||
#include <stdlib.h>
|
||
#include <string.h>
|
||
#include <sys/stat.h>
|
||
|
||
int main(int argc, char *argv[]) {
|
||
int i, j, ch;
|
||
const char *strip_prefix = "";
|
||
|
||
printf("// Auto-generated — DO NOT EDIT\n");
|
||
printf("#include \"mongoose.h\"\n");
|
||
printf("\n");
|
||
|
||
for (i = 1; i < argc; i++) {
|
||
if (strcmp(argv[i], "-s") == 0) {
|
||
strip_prefix = argv[++i];
|
||
} else if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0) {
|
||
fprintf(stderr, "Usage: %s [-s STRIP_PREFIX] files...\n", argv[0]);
|
||
exit(EXIT_FAILURE);
|
||
} else {
|
||
char ascii[16];
|
||
FILE *fp = fopen(argv[i], "rb");
|
||
if (fp == NULL) {
|
||
fprintf(stderr, "Cannot open [%s]: %s\n", argv[i], strerror(errno));
|
||
exit(EXIT_FAILURE);
|
||
}
|
||
|
||
printf("static const unsigned char v%d[] = {\n", i);
|
||
for (j = 0; (ch = fgetc(fp)) != EOF; j++) {
|
||
if (j == (int) sizeof(ascii)) {
|
||
printf(" // %.*s\n", j, ascii);
|
||
j = 0;
|
||
}
|
||
ascii[j] = (char) ((ch >= ' ' && ch <= '~' && ch != '\\') ? ch : '.');
|
||
printf(" %3u,", ch);
|
||
}
|
||
printf(" 0 // %.*s\n};\n", j, ascii);
|
||
fclose(fp);
|
||
}
|
||
}
|
||
|
||
printf("\nconst struct mg_mem_file mg_packed_files[] = {\n");
|
||
|
||
for (i = 1; i < argc; i++) {
|
||
struct stat st;
|
||
const char *name = argv[i];
|
||
size_t n = strlen(strip_prefix);
|
||
if (strcmp(argv[i], "-s") == 0) { i++; continue; }
|
||
stat(argv[i], &st);
|
||
if (strncmp(name, strip_prefix, n) == 0) name += n;
|
||
printf(" {\"/%s\", v%d, sizeof(v%d) - 1, %lu},\n",
|
||
name, i, i, (unsigned long) st.st_mtime);
|
||
}
|
||
printf(" {NULL, NULL, 0, 0}\n");
|
||
printf("};\n");
|
||
|
||
return EXIT_SUCCESS;
|
||
}
|