Unnamed: 0
int64 0
0
| repo_id
stringlengths 5
186
| file_path
stringlengths 15
223
| content
stringlengths 1
32.8M
⌀ |
---|---|---|---|
0 | repos/xmake/core/src/xmake | repos/xmake/core/src/xmake/lz4/decompress_stream_write.c | /*!A cross-platform build utility based on Lua
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright (C) 2015-present, TBOOX Open Source Group.
*
* @author ruki
* @file decompress_stream_write.c
*
*/
/* //////////////////////////////////////////////////////////////////////////////////////
* trace
*/
#define TB_TRACE_MODULE_NAME "decompress_stream_write"
#define TB_TRACE_MODULE_DEBUG (0)
/* //////////////////////////////////////////////////////////////////////////////////////
* includes
*/
#include "prefix.h"
/* //////////////////////////////////////////////////////////////////////////////////////
* implementation
*/
tb_int_t xm_lz4_decompress_stream_write(lua_State* lua)
{
// check
tb_assert_and_check_return_val(lua, 0);
// check handle
if (!xm_lua_ispointer(lua, 1))
{
lua_pushinteger(lua, -1);
lua_pushliteral(lua, "invalid handle!");
return 2;
}
// get stream
xm_lz4_dstream_t* stream = (xm_lz4_dstream_t*)xm_lua_topointer(lua, 1);
tb_check_return_val(stream, 0);
// get data and size
tb_size_t size = 0;
tb_byte_t const* data = tb_null;
if (xm_lua_isinteger(lua, 2)) data = (tb_byte_t const*)(tb_size_t)(tb_long_t)lua_tointeger(lua, 2);
if (xm_lua_isinteger(lua, 3)) size = (tb_size_t)lua_tointeger(lua, 3);
if (!data || !size)
{
lua_pushinteger(lua, -1);
lua_pushfstring(lua, "invalid data(%p) and size(%d)!", data, (tb_int_t)size);
return 2;
}
tb_assert_static(sizeof(lua_Integer) >= sizeof(tb_pointer_t));
// write data
tb_long_t real = xm_lz4_dstream_write(stream, data, size, tb_false);
lua_pushinteger(lua, (tb_int_t)real);
return 1;
}
|
0 | repos/xmake/core/src/xmake | repos/xmake/core/src/xmake/lz4/decompress_stream_close.c | /*!A cross-platform build utility based on Lua
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright (C) 2015-present, TBOOX Open Source Group.
*
* @author ruki
* @file decompress_stream_close.c
*
*/
/* //////////////////////////////////////////////////////////////////////////////////////
* trace
*/
#define TB_TRACE_MODULE_NAME "decompress_stream_close"
#define TB_TRACE_MODULE_DEBUG (0)
/* //////////////////////////////////////////////////////////////////////////////////////
* includes
*/
#include "prefix.h"
/* //////////////////////////////////////////////////////////////////////////////////////
* implementation
*/
tb_int_t xm_lz4_decompress_stream_close(lua_State* lua)
{
// check
tb_assert_and_check_return_val(lua, 0);
// is pointer?
if (!xm_lua_ispointer(lua, 1))
return 0;
// get the stream
xm_lz4_dstream_t* stream = (xm_lz4_dstream_t*)xm_lua_topointer(lua, 1);
tb_check_return_val(stream, 0);
// exit stream
xm_lz4_dstream_exit(stream);
// save result: ok
lua_pushboolean(lua, tb_true);
return 1;
}
|
0 | repos/xmake/core/src/xmake | repos/xmake/core/src/xmake/lz4/decompress_file.c | /*!A cross-platform build utility based on Lua
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright (C) 2015-present, TBOOX Open Source Group.
*
* @author ruki
* @file dedecompress_file.c
*
*/
/* //////////////////////////////////////////////////////////////////////////////////////
* trace
*/
#define TB_TRACE_MODULE_NAME "dedecompress_file"
#define TB_TRACE_MODULE_DEBUG (0)
/* //////////////////////////////////////////////////////////////////////////////////////
* includes
*/
#include "prefix.h"
/* //////////////////////////////////////////////////////////////////////////////////////
* implementation
*/
tb_int_t xm_lz4_decompress_file(lua_State* lua)
{
// check
tb_assert_and_check_return_val(lua, 0);
// get the file paths
tb_char_t const* srcpath = luaL_checkstring(lua, 1);
tb_char_t const* dstpath = luaL_checkstring(lua, 2);
tb_check_return_val(srcpath && dstpath, 0);
// init lz4 stream
xm_lz4_dstream_t* stream_lz4 = xm_lz4_dstream_init();
tb_check_return_val(stream_lz4, 0);
// do decompress
tb_bool_t ok = tb_false;
tb_stream_ref_t istream = tb_stream_init_from_file(srcpath, TB_FILE_MODE_RO);
tb_stream_ref_t ostream = tb_stream_init_from_file(dstpath, TB_FILE_MODE_RW | TB_FILE_MODE_CREAT | TB_FILE_MODE_TRUNC);
if (istream && ostream && tb_stream_open(istream) && tb_stream_open(ostream))
{
tb_bool_t write_ok = tb_false;
tb_byte_t idata[TB_STREAM_BLOCK_MAXN];
tb_byte_t odata[TB_STREAM_BLOCK_MAXN];
while (!tb_stream_beof(istream))
{
write_ok = tb_false;
tb_long_t ireal = (tb_long_t)tb_stream_read(istream, idata, sizeof(idata));
if (ireal > 0)
{
tb_long_t r = xm_lz4_dstream_write(stream_lz4, idata, ireal, tb_stream_beof(istream));
tb_assert_and_check_break(r >= 0);
tb_check_continue(r > 0);
tb_long_t oreal;
while ((oreal = xm_lz4_dstream_read(stream_lz4, odata, sizeof(odata))) > 0)
{
if (!tb_stream_bwrit(ostream, odata, oreal))
{
oreal = -1;
break;
}
}
tb_assert_and_check_break(oreal >= 0);
}
else break;
write_ok = tb_true;
}
if (tb_stream_beof(istream) && write_ok)
ok = tb_true;
}
// exit stream
if (istream)
{
tb_stream_exit(istream);
istream = tb_null;
}
if (ostream)
{
tb_stream_exit(ostream);
ostream = tb_null;
}
xm_lz4_dstream_exit(stream_lz4);
// ok?
lua_pushboolean(lua, ok);
return 1;
}
|
0 | repos/xmake/core/src/xmake | repos/xmake/core/src/xmake/lz4/prefix.h | /*!A cross-platform build utility based on Lua
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except idata compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to idata writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright (C) 2015-present, TBOOX Open Source Group.
*
* @author ruki
* @file prefix.h
*
*/
#ifndef XM_LZ4_PREFIX_H
#define XM_LZ4_PREFIX_H
/* //////////////////////////////////////////////////////////////////////////////////////
* includes
*/
#include "../prefix.h"
#include "lz4frame.h"
#include "lz4.h"
#include "lz4hc.h"
/* //////////////////////////////////////////////////////////////////////////////////////
* types
*/
// we need to define LZ4_byte if < 1.9.3
#if defined(LZ4_VERSION_NUMBER) && LZ4_VERSION_NUMBER < (1 * 100 * 100 + 9 * 100 + 3)
# if defined(__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */)
# include <stdint.h>
typedef int8_t LZ4_i8;
typedef uint8_t LZ4_byte;
typedef uint16_t LZ4_u16;
typedef uint32_t LZ4_u32;
# else
typedef signed char LZ4_i8;
typedef unsigned char LZ4_byte;
typedef unsigned short LZ4_u16;
typedef unsigned int LZ4_u32;
# endif
#endif
/* //////////////////////////////////////////////////////////////////////////////////////
* types
*/
// the lz4 compress stream type
typedef struct __xm_lz4_cstream_t
{
LZ4F_cctx* cctx;
LZ4_byte* buffer;
tb_size_t buffer_size;
tb_size_t buffer_maxn;
tb_size_t write_maxn;
tb_size_t header_size;
LZ4_byte header[LZ4F_HEADER_SIZE_MAX];
}xm_lz4_cstream_t;
// the lz4 decompress stream type
typedef struct __xm_lz4_dstream_t
{
LZ4F_dctx* dctx;
LZ4_byte* buffer;
tb_size_t buffer_size;
tb_size_t buffer_maxn;
tb_size_t header_size;
LZ4_byte header[LZ4F_HEADER_SIZE_MAX];
}xm_lz4_dstream_t;
/* //////////////////////////////////////////////////////////////////////////////////////
* interfaces
*/
static __tb_inline__ tb_void_t xm_lz4_cstream_exit(xm_lz4_cstream_t* stream)
{
if (stream)
{
if (stream->cctx)
{
LZ4F_freeCompressionContext(stream->cctx);
stream->cctx = tb_null;
}
if (stream->buffer)
{
tb_free(stream->buffer);
stream->buffer = tb_null;
}
tb_free(stream);
}
}
static __tb_inline__ xm_lz4_cstream_t* xm_lz4_cstream_init()
{
tb_size_t ret;
tb_bool_t ok = tb_false;
xm_lz4_cstream_t* stream = tb_null;
LZ4F_preferences_t const* prefsPtr = tb_null;
do
{
stream = tb_malloc0_type(xm_lz4_cstream_t);
tb_assert_and_check_break(stream);
stream->write_maxn = 64 * 1024;
stream->buffer_maxn = LZ4F_compressBound(stream->write_maxn, prefsPtr);
stream->buffer = (LZ4_byte*)tb_malloc(stream->buffer_maxn);
tb_assert_and_check_break(stream->buffer);
ret = LZ4F_createCompressionContext(&stream->cctx, LZ4F_getVersion());
if (LZ4F_isError(ret))
break;
ret = LZ4F_compressBegin(stream->cctx, stream->header, LZ4F_HEADER_SIZE_MAX, prefsPtr);
if (LZ4F_isError(ret))
break;
stream->header_size = ret;
ok = tb_true;
} while (0);
if (!ok && stream)
{
xm_lz4_cstream_exit(stream);
stream = tb_null;
}
return stream;
}
static __tb_inline__ tb_long_t xm_lz4_cstream_write(xm_lz4_cstream_t* stream, tb_byte_t const* idata, tb_size_t isize, tb_bool_t end)
{
// check
tb_assert_and_check_return_val(stream && stream->cctx && idata && isize, -1);
tb_assert_and_check_return_val(isize <= stream->write_maxn, -1);
tb_assert_and_check_return_val(stream->buffer_size + isize < stream->buffer_maxn, -1);
tb_size_t real = LZ4F_compressUpdate(stream->cctx, stream->buffer + stream->buffer_size,
stream->buffer_maxn - stream->buffer_size, idata, isize, tb_null);
if (LZ4F_isError(real))
return -1;
stream->buffer_size += real;
if (end)
{
tb_size_t ret = LZ4F_compressEnd(stream->cctx, stream->buffer + stream->buffer_size,
stream->buffer_maxn - stream->buffer_size, tb_null);
if (LZ4F_isError(ret))
return -1;
real += ret;
stream->buffer_size += ret;
}
return isize;
}
static __tb_inline__ tb_long_t xm_lz4_cstream_read(xm_lz4_cstream_t* stream, tb_byte_t* odata, tb_size_t osize)
{
// check
tb_assert_and_check_return_val(stream && stream->cctx && odata && osize, -1);
tb_assert_and_check_return_val(osize >= stream->header_size, -1);
tb_size_t read = 0;
if (stream->header_size)
{
tb_memcpy(odata, stream->header, stream->header_size);
read += stream->header_size;
osize -= stream->header_size;
stream->header_size = 0;
}
tb_size_t need = tb_min(stream->buffer_size, osize);
tb_memcpy(odata + read, stream->buffer, need);
if (need < stream->buffer_size)
tb_memmov(stream->buffer, stream->buffer + need, stream->buffer_size - need);
stream->buffer_size -= need;
read += need;
return read;
}
static __tb_inline__ tb_void_t xm_lz4_dstream_exit(xm_lz4_dstream_t* stream)
{
if (stream)
{
if (stream->dctx)
{
LZ4F_freeDecompressionContext(stream->dctx);
stream->dctx = tb_null;
}
if (stream->buffer)
{
tb_free(stream->buffer);
stream->buffer = tb_null;
}
tb_free(stream);
}
}
static __tb_inline__ xm_lz4_dstream_t* xm_lz4_dstream_init()
{
LZ4F_errorCode_t ret;
tb_bool_t ok = tb_false;
xm_lz4_dstream_t* stream = tb_null;
do
{
stream = tb_malloc0_type(xm_lz4_dstream_t);
tb_assert_and_check_break(stream);
ret = LZ4F_createDecompressionContext(&stream->dctx, LZ4F_getVersion());
if (LZ4F_isError(ret))
break;
ok = tb_true;
} while (0);
if (!ok && stream)
{
xm_lz4_dstream_exit(stream);
stream = tb_null;
}
return stream;
}
static __tb_inline__ tb_long_t xm_lz4_dstream_write(xm_lz4_dstream_t* stream, tb_byte_t const* idata, tb_size_t isize, tb_bool_t end)
{
// check
tb_assert_and_check_return_val(stream && stream->dctx && idata && isize, -1);
// read header first
const tb_size_t header_size = sizeof(stream->header);
if (stream->header_size < header_size)
{
tb_size_t size = tb_min(header_size - stream->header_size, isize);
tb_memcpy(stream->header + stream->header_size, idata, size);
stream->header_size += size;
idata += size;
isize -= size;
// get frame info if header is ok
if (stream->header_size == header_size)
{
LZ4F_frameInfo_t info;
size_t consumed_size = header_size;
LZ4F_errorCode_t ret = LZ4F_getFrameInfo(stream->dctx, &info, stream->header, &consumed_size);
if (LZ4F_isError(ret))
return -1;
switch (info.blockSizeID)
{
case LZ4F_default:
case LZ4F_max64KB:
stream->buffer_maxn = 64 * 1024;
break;
case LZ4F_max256KB:
stream->buffer_maxn = 256 * 1024;
break;
case LZ4F_max1MB:
stream->buffer_maxn = 1 * 1024 * 1024;
break;
case LZ4F_max4MB:
stream->buffer_maxn = 4 * 1024 * 1024;
break;
default:
return -1;
}
stream->buffer = (LZ4_byte*)tb_malloc(stream->buffer_maxn);
tb_assert_and_check_return_val(stream->buffer, -1);
stream->buffer_size = header_size - consumed_size;
tb_memcpy(stream->buffer, stream->header + consumed_size, stream->buffer_size);
}
}
tb_check_return_val(stream->header_size == header_size && isize, 0);
tb_assert_and_check_return_val(stream->buffer && stream->buffer_size + isize <= stream->buffer_maxn, -1);
// append the input data
tb_memcpy(stream->buffer + stream->buffer_size, idata, isize);
stream->buffer_size += isize;
return isize;
}
static __tb_inline__ tb_long_t xm_lz4_dstream_read(xm_lz4_dstream_t* stream, tb_byte_t* odata, tb_size_t osize)
{
// check
tb_assert_and_check_return_val(stream && stream->dctx && stream->buffer && odata && osize, -1);
tb_check_return_val(stream->buffer_size, 0);
// do decompress
size_t srcsize = stream->buffer_size;
size_t dstsize = osize;
tb_size_t ret = LZ4F_decompress(stream->dctx, odata, &dstsize, stream->buffer, &srcsize, tb_null);
if (LZ4F_isError(ret))
return -1;
// move the left input data
if (srcsize < stream->buffer_size)
tb_memmov(stream->buffer, stream->buffer + srcsize, stream->buffer_size - srcsize);
stream->buffer_size -= srcsize;
return dstsize;
}
#endif
|
0 | repos/xmake/core/src/xmake | repos/xmake/core/src/xmake/lz4/compress.c | /*!A cross-platform build utility based on Lua
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright (C) 2015-present, TBOOX Open Source Group.
*
* @author ruki
* @file compress.c
*
*/
/* //////////////////////////////////////////////////////////////////////////////////////
* trace
*/
#define TB_TRACE_MODULE_NAME "compress"
#define TB_TRACE_MODULE_DEBUG (0)
/* //////////////////////////////////////////////////////////////////////////////////////
* includes
*/
#include "prefix.h"
/* //////////////////////////////////////////////////////////////////////////////////////
* implementation
*/
tb_int_t xm_lz4_compress(lua_State* lua)
{
// check
tb_assert_and_check_return_val(lua, 0);
// get data and size
tb_size_t size = 0;
tb_byte_t const* data = tb_null;
if (xm_lua_isinteger(lua, 1)) data = (tb_byte_t const*)(tb_size_t)(tb_long_t)lua_tointeger(lua, 1);
if (xm_lua_isinteger(lua, 2)) size = (tb_size_t)lua_tointeger(lua, 2);
if (!data || !size)
{
lua_pushnil(lua);
lua_pushfstring(lua, "invalid data(%p) and size(%d)!", data, (tb_int_t)size);
return 2;
}
tb_assert_static(sizeof(lua_Integer) >= sizeof(tb_pointer_t));
// do compress
tb_bool_t ok = tb_false;
tb_char_t const* error = tb_null;
tb_byte_t* output_data = tb_null;
tb_byte_t buffer[8192];
do
{
tb_size_t output_size = LZ4F_compressFrameBound(size, tb_null);
tb_assert_and_check_break(output_size);
output_data = output_size <= sizeof(buffer)? buffer : (tb_byte_t*)tb_malloc(output_size);
tb_assert_and_check_break(output_data);
tb_size_t real_or_errs = LZ4F_compressFrame(output_data, output_size, data, size, tb_null);
if (LZ4F_isError(real_or_errs))
{
error = LZ4F_getErrorName(real_or_errs);
break;
}
lua_pushlstring(lua, (tb_char_t const*)output_data, real_or_errs);
ok = tb_true;
} while (0);
if (output_data && output_data != buffer)
{
tb_free(output_data);
output_data = tb_null;
}
if (!ok)
{
lua_pushnil(lua);
lua_pushstring(lua, error? error : "unknown");
return 2;
}
return 1;
}
|
0 | repos/xmake/core/src/xmake | repos/xmake/core/src/xmake/lz4/decompress_stream_read.c | /*!A cross-platform build utility based on Lua
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright (C) 2015-present, TBOOX Open Source Group.
*
* @author ruki
* @file decompress_stream_read.c
*
*/
/* //////////////////////////////////////////////////////////////////////////////////////
* trace
*/
#define TB_TRACE_MODULE_NAME "decompress_stream_read"
#define TB_TRACE_MODULE_DEBUG (0)
/* //////////////////////////////////////////////////////////////////////////////////////
* includes
*/
#include "prefix.h"
/* //////////////////////////////////////////////////////////////////////////////////////
* implementation
*/
tb_int_t xm_lz4_decompress_stream_read(lua_State* lua)
{
// check
tb_assert_and_check_return_val(lua, 0);
// check handle
if (!xm_lua_ispointer(lua, 1))
{
lua_pushinteger(lua, -1);
lua_pushliteral(lua, "invalid handle!");
return 2;
}
// get stream
xm_lz4_dstream_t* stream = (xm_lz4_dstream_t*)xm_lua_topointer(lua, 1);
tb_check_return_val(stream, 0);
// get data
tb_byte_t* data = tb_null;
if (xm_lua_isinteger(lua, 2))
data = (tb_byte_t*)(tb_size_t)(tb_long_t)lua_tointeger(lua, 2);
if (!data)
{
lua_pushinteger(lua, -1);
lua_pushfstring(lua, "invalid data(%p)!", data);
return 2;
}
tb_assert_static(sizeof(lua_Integer) >= sizeof(tb_pointer_t));
// get size
tb_long_t size = 0;
if (xm_lua_isinteger(lua, 3)) size = (tb_long_t)lua_tointeger(lua, 3);
if (size <= 0)
{
lua_pushinteger(lua, -1);
lua_pushfstring(lua, "invalid size(%d)!", (tb_int_t)size);
return 2;
}
// read data
tb_long_t real = xm_lz4_dstream_read(stream, data, size);
lua_pushinteger(lua, (tb_int_t)real);
return 1;
}
|
0 | repos/xmake/core/src/xmake | repos/xmake/core/src/xmake/lz4/block_decompress.c | /*!A cross-platform build utility based on Lua
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright (C) 2015-present, TBOOX Open Source Group.
*
* @author ruki
* @file block_decompress.c
*
*/
/* //////////////////////////////////////////////////////////////////////////////////////
* trace
*/
#define TB_TRACE_MODULE_NAME "block_decompress"
#define TB_TRACE_MODULE_DEBUG (0)
/* //////////////////////////////////////////////////////////////////////////////////////
* includes
*/
#include "prefix.h"
/* //////////////////////////////////////////////////////////////////////////////////////
* implementation
*/
tb_int_t xm_lz4_block_decompress(lua_State* lua)
{
// check
tb_assert_and_check_return_val(lua, 0);
// get data and size
tb_size_t size = 0;
tb_byte_t const* data = tb_null;
if (xm_lua_isinteger(lua, 1)) data = (tb_byte_t const*)(tb_size_t)(tb_long_t)lua_tointeger(lua, 1);
if (xm_lua_isinteger(lua, 2)) size = (tb_size_t)lua_tointeger(lua, 2);
if (!data || !size)
{
lua_pushnil(lua);
lua_pushfstring(lua, "invalid data(%p) and size(%d)!", data, (tb_int_t)size);
return 2;
}
tb_assert_static(sizeof(lua_Integer) >= sizeof(tb_pointer_t));
// get real size
tb_int_t real = (tb_int_t)lua_tointeger(lua, 3);
if (real <= 0)
{
lua_pushnil(lua);
lua_pushfstring(lua, "invalid output size(%d)!", real);
return 2;
}
// do decompress
tb_bool_t ok = tb_false;
tb_byte_t* output_data = tb_null;
tb_byte_t buffer[8192];
do
{
output_data = real <= sizeof(buffer)? buffer : (tb_byte_t*)tb_malloc(real);
tb_assert_and_check_break(output_data);
tb_int_t r = LZ4_decompress_safe((tb_char_t const*)data, (tb_char_t*)output_data, (tb_int_t)size, real);
tb_assert_and_check_break(r > 0);
lua_pushlstring(lua, (tb_char_t const*)output_data, r);
ok = tb_true;
} while (0);
if (output_data && output_data != buffer)
{
tb_free(output_data);
output_data = tb_null;
}
if (!ok) lua_pushnil(lua);
return 1;
}
|
0 | repos/xmake/core/src/xmake | repos/xmake/core/src/xmake/lz4/block_compress.c | /*!A cross-platform build utility based on Lua
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright (C) 2015-present, TBOOX Open Source Group.
*
* @author ruki
* @file block_compress.c
*
*/
/* //////////////////////////////////////////////////////////////////////////////////////
* trace
*/
#define TB_TRACE_MODULE_NAME "block_compress"
#define TB_TRACE_MODULE_DEBUG (0)
/* //////////////////////////////////////////////////////////////////////////////////////
* includes
*/
#include "prefix.h"
/* //////////////////////////////////////////////////////////////////////////////////////
* implementation
*/
tb_int_t xm_lz4_block_compress(lua_State* lua)
{
// check
tb_assert_and_check_return_val(lua, 0);
// get data and size
tb_int_t size = 0;
tb_byte_t const* data = tb_null;
if (xm_lua_isinteger(lua, 1)) data = (tb_byte_t const*)(tb_size_t)(tb_long_t)lua_tointeger(lua, 1);
if (xm_lua_isinteger(lua, 2)) size = (tb_int_t)lua_tointeger(lua, 2);
if (!data || !size || size > LZ4_MAX_INPUT_SIZE)
{
lua_pushnil(lua);
lua_pushfstring(lua, "invalid data(%p) and size(%d)!", data, (tb_int_t)size);
return 2;
}
tb_assert_static(sizeof(lua_Integer) >= sizeof(tb_pointer_t));
// do compress
tb_bool_t ok = tb_false;
tb_byte_t* output_data = tb_null;
tb_byte_t buffer[8192];
do
{
tb_int_t output_size = LZ4_compressBound(size);
tb_assert_and_check_break(output_size);
output_data = output_size <= sizeof(buffer)? buffer : (tb_byte_t*)tb_malloc(output_size);
tb_assert_and_check_break(output_data);
tb_int_t real = LZ4_compress_default((tb_char_t const*)data, (tb_char_t*)output_data, size, output_size);
tb_assert_and_check_break(real > 0);
lua_pushlstring(lua, (tb_char_t const*)output_data, real);
ok = tb_true;
} while (0);
if (output_data && output_data != buffer)
{
tb_free(output_data);
output_data = tb_null;
}
if (!ok) lua_pushnil(lua);
return 1;
}
|
0 | repos/xmake/core/src/xmake | repos/xmake/core/src/xmake/lz4/compress_stream_close.c | /*!A cross-platform build utility based on Lua
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright (C) 2015-present, TBOOX Open Source Group.
*
* @author ruki
* @file compress_stream_close.c
*
*/
/* //////////////////////////////////////////////////////////////////////////////////////
* trace
*/
#define TB_TRACE_MODULE_NAME "compress_stream_close"
#define TB_TRACE_MODULE_DEBUG (0)
/* //////////////////////////////////////////////////////////////////////////////////////
* includes
*/
#include "prefix.h"
/* //////////////////////////////////////////////////////////////////////////////////////
* implementation
*/
tb_int_t xm_lz4_compress_stream_close(lua_State* lua)
{
// check
tb_assert_and_check_return_val(lua, 0);
// is pointer?
if (!xm_lua_ispointer(lua, 1))
return 0;
// get the stream
xm_lz4_cstream_t* stream = (xm_lz4_cstream_t*)xm_lua_topointer(lua, 1);
tb_check_return_val(stream, 0);
// exit stream
xm_lz4_cstream_exit(stream);
// save result: ok
lua_pushboolean(lua, tb_true);
return 1;
}
|
0 | repos/xmake/core/src/xmake | repos/xmake/core/src/xmake/lz4/compress_stream_open.c | /*!A cross-platform build utility based on Lua
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright (C) 2015-present, TBOOX Open Source Group.
*
* @author ruki
* @file compress_stream_open.c
*
*/
/* //////////////////////////////////////////////////////////////////////////////////////
* trace
*/
#define TB_TRACE_MODULE_NAME "compress_stream_open"
#define TB_TRACE_MODULE_DEBUG (0)
/* //////////////////////////////////////////////////////////////////////////////////////
* includes
*/
#include "prefix.h"
/* //////////////////////////////////////////////////////////////////////////////////////
* implementation
*/
tb_int_t xm_lz4_compress_stream_open(lua_State* lua)
{
// check
tb_assert_and_check_return_val(lua, 0);
xm_lz4_cstream_t* stream = xm_lz4_cstream_init();
if (stream) xm_lua_pushpointer(lua, (tb_pointer_t)stream);
else lua_pushnil(lua);
return 1;
}
|
0 | repos/xmake/core/src/xmake | repos/xmake/core/src/xmake/lz4/compress_file.c | /*!A cross-platform build utility based on Lua
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright (C) 2015-present, TBOOX Open Source Group.
*
* @author ruki
* @file compress_file.c
*
*/
/* //////////////////////////////////////////////////////////////////////////////////////
* trace
*/
#define TB_TRACE_MODULE_NAME "compress_file"
#define TB_TRACE_MODULE_DEBUG (0)
/* //////////////////////////////////////////////////////////////////////////////////////
* includes
*/
#include "prefix.h"
/* //////////////////////////////////////////////////////////////////////////////////////
* implementation
*/
tb_int_t xm_lz4_compress_file(lua_State* lua)
{
// check
tb_assert_and_check_return_val(lua, 0);
// get the file paths
tb_char_t const* srcpath = luaL_checkstring(lua, 1);
tb_char_t const* dstpath = luaL_checkstring(lua, 2);
tb_check_return_val(srcpath && dstpath, 0);
// init lz4 stream
xm_lz4_cstream_t* stream_lz4 = xm_lz4_cstream_init();
tb_check_return_val(stream_lz4, 0);
// do compress
tb_bool_t ok = tb_false;
tb_stream_ref_t istream = tb_stream_init_from_file(srcpath, TB_FILE_MODE_RO);
tb_stream_ref_t ostream = tb_stream_init_from_file(dstpath, TB_FILE_MODE_RW | TB_FILE_MODE_CREAT | TB_FILE_MODE_TRUNC);
if (istream && ostream && tb_stream_open(istream) && tb_stream_open(ostream))
{
tb_bool_t write_ok = tb_false;
tb_byte_t idata[TB_STREAM_BLOCK_MAXN];
tb_byte_t odata[TB_STREAM_BLOCK_MAXN];
while (!tb_stream_beof(istream))
{
write_ok = tb_false;
tb_long_t ireal = (tb_long_t)tb_stream_read(istream, idata, sizeof(idata));
if (ireal > 0)
{
tb_long_t r = xm_lz4_cstream_write(stream_lz4, idata, ireal, tb_stream_beof(istream));
tb_assert_and_check_break(r >= 0);
tb_check_continue(r > 0);
tb_long_t oreal;
while ((oreal = xm_lz4_cstream_read(stream_lz4, odata, sizeof(odata))) > 0)
{
if (!tb_stream_bwrit(ostream, odata, oreal))
{
oreal = -1;
break;
}
}
tb_assert_and_check_break(oreal >= 0);
}
else break;
write_ok = tb_true;
}
if (tb_stream_beof(istream) && write_ok)
ok = tb_true;
}
// exit stream
if (istream)
{
tb_stream_exit(istream);
istream = tb_null;
}
if (ostream)
{
tb_stream_exit(ostream);
ostream = tb_null;
}
xm_lz4_cstream_exit(stream_lz4);
// ok?
lua_pushboolean(lua, ok);
return 1;
}
|
0 | repos/xmake/core/src/xmake | repos/xmake/core/src/xmake/curses/prefix.h | /*!A cross-platform build utility based on Lua
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright (C) 2015-present, TBOOX Open Source Group.
*
* @author uael
* @file prefix.h
*
*/
#ifndef XM_CURSES_PREFIX_H
#define XM_CURSES_PREFIX_H
/* //////////////////////////////////////////////////////////////////////////////////////
* includes
*/
#include "../prefix.h"
#endif
|
0 | repos/xmake/core/src/xmake | repos/xmake/core/src/xmake/curses/curses.c | /*!A cross-platform build utility based on Lua
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright (C) 2015-present, TBOOX Open Source Group.
*
* @author ruki
* @file curses.c
*
*/
/* //////////////////////////////////////////////////////////////////////////////////////
* trace
*/
#define TB_TRACE_MODULE_NAME "curses"
#define TB_TRACE_MODULE_DEBUG (0)
/* //////////////////////////////////////////////////////////////////////////////////////
* includes
*/
#ifdef XM_CONFIG_API_HAVE_CURSES
#include "prefix.h"
#include <stdlib.h>
#if defined(PDCURSES)
// fix macro redefinition
# undef MOUSE_MOVED
#endif
#define NCURSES_MOUSE_VERSION 2
#ifdef TB_COMPILER_IS_MINGW
# include <ncursesw/curses.h>
#else
# include <curses.h>
#endif
#if defined(NCURSES_VERSION)
# include <locale.h>
#endif
/* //////////////////////////////////////////////////////////////////////////////////////
* macros
*/
#define XM_CURSES_STDSCR "curses.stdscr"
#define XM_CURSES_WINDOW "curses.window"
#define XM_CURSES_OK(v) (((v) == ERR) ? 0 : 1)
// define functions
#define XM_CURSES_NUMBER(n) \
static int xm_curses_ ## n(lua_State* lua) \
{ \
lua_pushnumber(lua, n()); \
return 1; \
}
#define XM_CURSES_NUMBER2(n, v) \
static int xm_curses_ ## n(lua_State* lua) \
{ \
lua_pushnumber(lua, v); \
return 1; \
}
#define XM_CURSES_BOOL(n) \
static int xm_curses_ ## n(lua_State* lua) \
{ \
lua_pushboolean(lua, n()); \
return 1; \
}
#define XM_CURSES_BOOLOK(n) \
static int xm_curses_ ## n(lua_State* lua) \
{ \
lua_pushboolean(lua, XM_CURSES_OK(n())); \
return 1; \
}
#define XM_CURSES_WINDOW_BOOLOK(n) \
static int xm_curses_window_ ## n(lua_State* lua) \
{ \
WINDOW* w = xm_curses_window_check(lua, 1); \
lua_pushboolean(lua, XM_CURSES_OK(n(w))); \
return 1; \
}
// define constants
#define XM_CURSES_CONST_(n, v) \
lua_pushstring(lua, n); \
lua_pushnumber(lua, v); \
lua_settable(lua, lua_upvalueindex(1));
#define XM_CURSES_CONST(s) XM_CURSES_CONST_(#s, s)
#define XM_CURSES_CONST2(s, v) XM_CURSES_CONST_(#s, v)
/* //////////////////////////////////////////////////////////////////////////////////////
* globals
*/
// map key for pdcurses, keeping the keys consistent with ncurses
static int g_mapkey = 0;
/* //////////////////////////////////////////////////////////////////////////////////////
* private implementation
*/
static chtype xm_curses_checkch(lua_State* lua, int index)
{
if (lua_type(lua, index) == LUA_TNUMBER)
return (chtype)luaL_checknumber(lua, index);
if (lua_type(lua, index) == LUA_TSTRING)
return *lua_tostring(lua, index);
#ifdef USE_LUAJIT
luaL_typerror(lua, index, "chtype");
#endif
return (chtype)0;
}
// get character and map key
static int xm_curses_window_getch_impl(WINDOW* w)
{
#ifdef PDCURSES
static int has_key = 0;
static int temp_key = 0;
int key;
if (g_mapkey && has_key)
{
has_key = 0;
return temp_key;
}
key = wgetch(w);
if (key == KEY_RESIZE) resize_term(0, 0);
if (key == ERR || !g_mapkey) return key;
if (key >= ALT_A && key <= ALT_Z)
{
has_key = 1;
temp_key = key - ALT_A + 'A';
}
else if (key >= ALT_0 && key <= ALT_9)
{
has_key = 1;
temp_key = key - ALT_0 + '0';
}
else
{
switch (key)
{
case ALT_DEL: temp_key = KEY_DC; break;
case ALT_INS: temp_key = KEY_IC; break;
case ALT_HOME: temp_key = KEY_HOME; break;
case ALT_END: temp_key = KEY_END; break;
case ALT_PGUP: temp_key = KEY_PPAGE; break;
case ALT_PGDN: temp_key = KEY_NPAGE; break;
case ALT_UP: temp_key = KEY_UP; break;
case ALT_DOWN: temp_key = KEY_DOWN; break;
case ALT_RIGHT: temp_key = KEY_RIGHT; break;
case ALT_LEFT: temp_key = KEY_LEFT; break;
case ALT_BKSP: temp_key = KEY_BACKSPACE; break;
default: return key;
}
}
has_key = 1;
return 27;
#else
return wgetch(w);
#endif
}
// new a window object
static void xm_curses_window_new(lua_State* lua, WINDOW* nw)
{
if (nw)
{
WINDOW** w = (WINDOW**)lua_newuserdata(lua, sizeof(WINDOW*));
luaL_getmetatable(lua, XM_CURSES_WINDOW);
lua_setmetatable(lua, -2);
*w = nw;
}
else
{
lua_pushliteral(lua, "failed to create window");
lua_error(lua);
}
}
// get window
static WINDOW** xm_curses_window_get(lua_State* lua, int index)
{
WINDOW** w = (WINDOW**)luaL_checkudata(lua, index, XM_CURSES_WINDOW);
if (w == NULL) luaL_argerror(lua, index, "bad curses window");
return w;
}
// get and check window
static WINDOW* xm_curses_window_check(lua_State* lua, int index)
{
WINDOW** w = xm_curses_window_get(lua, index);
if (*w == NULL) luaL_argerror(lua, index, "attempt to use closed curses window");
return *w;
}
// tostring(window)
static int xm_curses_window_tostring(lua_State* lua)
{
WINDOW** w = xm_curses_window_get(lua, 1);
char const* s = NULL;
if (*w) s = (char const*)lua_touserdata(lua, 1);
lua_pushfstring(lua, "curses window (%s)", s? s : "closed");
return 1;
}
// window:move(y, x)
static int xm_curses_window_move(lua_State* lua)
{
WINDOW* w = xm_curses_window_check(lua, 1);
int y = luaL_checkint(lua, 2);
int x = luaL_checkint(lua, 3);
lua_pushboolean(lua, XM_CURSES_OK(wmove(w, y, x)));
return 1;
}
// window:getyx(y, x)
static int xm_curses_window_getyx(lua_State* lua)
{
WINDOW* w = xm_curses_window_check(lua, 1);
int y, x;
getyx(w, y, x);
lua_pushnumber(lua, y);
lua_pushnumber(lua, x);
return 2;
}
// window:getmaxyx(y, x)
static int xm_curses_window_getmaxyx(lua_State* lua)
{
WINDOW* w = xm_curses_window_check(lua, 1);
int y, x;
getmaxyx(w, y, x);
lua_pushnumber(lua, y);
lua_pushnumber(lua, x);
return 2;
}
// window:delwin()
static int xm_curses_window_delwin(lua_State* lua)
{
WINDOW** w = xm_curses_window_get(lua, 1);
if (*w && *w != stdscr)
{
delwin(*w);
*w = NULL;
}
return 0;
}
// window:addch(ch)
static int xm_curses_window_addch(lua_State* lua)
{
WINDOW* w = xm_curses_window_check(lua, 1);
chtype ch = xm_curses_checkch(lua, 2);
lua_pushboolean(lua, XM_CURSES_OK(waddch(w, ch)));
return 1;
}
// window:addnstr(str)
static int xm_curses_window_addnstr(lua_State* lua)
{
WINDOW* w = xm_curses_window_check(lua, 1);
const char* str = luaL_checkstring(lua, 2);
int n = luaL_optint(lua, 3, -1);
if (n < 0) n = (int)lua_strlen(lua, 2);
lua_pushboolean(lua, XM_CURSES_OK(waddnstr(w, str, n)));
return 1;
}
// window:keypad(true)
static int xm_curses_window_keypad(lua_State* lua)
{
WINDOW* w = xm_curses_window_check(lua, 1);
int enabled = lua_isnoneornil(lua, 2) ? 1 : lua_toboolean(lua, 2);
if (enabled)
{
// on WIN32 ALT keys need to be mapped, so to make sure you get the wanted keys,
// only makes sense when using keypad(true) and echo(false)
g_mapkey = 1;
}
lua_pushboolean(lua, XM_CURSES_OK(keypad(w, enabled)));
return 1;
}
// window:meta(true)
static int xm_curses_window_meta(lua_State* lua)
{
WINDOW* w = xm_curses_window_check(lua, 1);
int enabled = lua_toboolean(lua, 2);
lua_pushboolean(lua, XM_CURSES_OK(meta(w, enabled)));
return 1;
}
// window:nodelay(true)
static int xm_curses_window_nodelay(lua_State* lua)
{
WINDOW* w = xm_curses_window_check(lua, 1);
int enabled = lua_toboolean(lua, 2);
lua_pushboolean(lua, XM_CURSES_OK(nodelay(w, enabled)));
return 1;
}
// window:leaveok(true)
static int xm_curses_window_leaveok(lua_State* lua)
{
WINDOW* w = xm_curses_window_check(lua, 1);
int enabled = lua_toboolean(lua, 2);
lua_pushboolean(lua, XM_CURSES_OK(leaveok(w, enabled)));
return 1;
}
// window:getch()
static int xm_curses_window_getch(lua_State* lua)
{
WINDOW* w = xm_curses_window_check(lua, 1);
int c = xm_curses_window_getch_impl(w);
if (c == ERR) return 0;
lua_pushnumber(lua, c);
return 1;
}
// window:attroff(attrs)
static int xm_curses_window_attroff(lua_State* lua)
{
WINDOW* w = xm_curses_window_check(lua, 1);
int attrs = luaL_checkint(lua, 2);
lua_pushboolean(lua, XM_CURSES_OK(wattroff(w, attrs)));
return 1;
}
// window:attron(attrs)
static int xm_curses_window_attron(lua_State* lua)
{
WINDOW* w = xm_curses_window_check(lua, 1);
int attrs = luaL_checkint(lua, 2);
lua_pushboolean(lua, XM_CURSES_OK(wattron(w, attrs)));
return 1;
}
// window:attrset(attrs)
static int xm_curses_window_attrset(lua_State* lua)
{
WINDOW* w = xm_curses_window_check(lua, 1);
int attrs = luaL_checkint(lua, 2);
lua_pushboolean(lua, XM_CURSES_OK(wattrset(w, attrs)));
return 1;
}
// window:copywin(...)
static int xm_curses_window_copywin(lua_State* lua)
{
WINDOW* srcwin = xm_curses_window_check(lua, 1);
WINDOW* dstwin = xm_curses_window_check(lua, 2);
int sminrow = luaL_checkint(lua, 3);
int smincol = luaL_checkint(lua, 4);
int dminrow = luaL_checkint(lua, 5);
int dmincol = luaL_checkint(lua, 6);
int dmaxrow = luaL_checkint(lua, 7);
int dmaxcol = luaL_checkint(lua, 8);
int overlay = lua_toboolean(lua, 9);
lua_pushboolean(lua, XM_CURSES_OK(copywin(srcwin, dstwin, sminrow,
smincol, dminrow, dmincol, dmaxrow, dmaxcol, overlay)));
return 1;
}
// clean window after exiting program
static void xm_curses_cleanup()
{
if (!isendwin())
{
wclear(stdscr);
wrefresh(stdscr);
endwin();
}
}
// register constants
static void xm_curses_register_constants(lua_State* lua)
{
// colors
XM_CURSES_CONST(COLOR_BLACK)
XM_CURSES_CONST(COLOR_RED)
XM_CURSES_CONST(COLOR_GREEN)
XM_CURSES_CONST(COLOR_YELLOW)
XM_CURSES_CONST(COLOR_BLUE)
XM_CURSES_CONST(COLOR_MAGENTA)
XM_CURSES_CONST(COLOR_CYAN)
XM_CURSES_CONST(COLOR_WHITE)
// alternate character set
XM_CURSES_CONST(ACS_BLOCK)
XM_CURSES_CONST(ACS_BOARD)
XM_CURSES_CONST(ACS_BTEE)
XM_CURSES_CONST(ACS_TTEE)
XM_CURSES_CONST(ACS_LTEE)
XM_CURSES_CONST(ACS_RTEE)
XM_CURSES_CONST(ACS_LLCORNER)
XM_CURSES_CONST(ACS_LRCORNER)
XM_CURSES_CONST(ACS_URCORNER)
XM_CURSES_CONST(ACS_ULCORNER)
XM_CURSES_CONST(ACS_LARROW)
XM_CURSES_CONST(ACS_RARROW)
XM_CURSES_CONST(ACS_UARROW)
XM_CURSES_CONST(ACS_DARROW)
XM_CURSES_CONST(ACS_HLINE)
XM_CURSES_CONST(ACS_VLINE)
XM_CURSES_CONST(ACS_BULLET)
XM_CURSES_CONST(ACS_CKBOARD)
XM_CURSES_CONST(ACS_LANTERN)
XM_CURSES_CONST(ACS_DEGREE)
XM_CURSES_CONST(ACS_DIAMOND)
XM_CURSES_CONST(ACS_PLMINUS)
XM_CURSES_CONST(ACS_PLUS)
XM_CURSES_CONST(ACS_S1)
XM_CURSES_CONST(ACS_S9)
// attributes
XM_CURSES_CONST(A_NORMAL)
XM_CURSES_CONST(A_STANDOUT)
XM_CURSES_CONST(A_UNDERLINE)
XM_CURSES_CONST(A_REVERSE)
XM_CURSES_CONST(A_BLINK)
XM_CURSES_CONST(A_DIM)
XM_CURSES_CONST(A_BOLD)
XM_CURSES_CONST(A_PROTECT)
XM_CURSES_CONST(A_INVIS)
XM_CURSES_CONST(A_ALTCHARSET)
XM_CURSES_CONST(A_CHARTEXT)
// key functions
XM_CURSES_CONST(KEY_BREAK)
XM_CURSES_CONST(KEY_DOWN)
XM_CURSES_CONST(KEY_UP)
XM_CURSES_CONST(KEY_LEFT)
XM_CURSES_CONST(KEY_RIGHT)
XM_CURSES_CONST(KEY_HOME)
XM_CURSES_CONST(KEY_BACKSPACE)
XM_CURSES_CONST(KEY_DL)
XM_CURSES_CONST(KEY_IL)
XM_CURSES_CONST(KEY_DC)
XM_CURSES_CONST(KEY_IC)
XM_CURSES_CONST(KEY_EIC)
XM_CURSES_CONST(KEY_CLEAR)
XM_CURSES_CONST(KEY_EOS)
XM_CURSES_CONST(KEY_EOL)
XM_CURSES_CONST(KEY_SF)
XM_CURSES_CONST(KEY_SR)
XM_CURSES_CONST(KEY_NPAGE)
XM_CURSES_CONST(KEY_PPAGE)
XM_CURSES_CONST(KEY_STAB)
XM_CURSES_CONST(KEY_CTAB)
XM_CURSES_CONST(KEY_CATAB)
XM_CURSES_CONST(KEY_ENTER)
XM_CURSES_CONST(KEY_SRESET)
XM_CURSES_CONST(KEY_RESET)
XM_CURSES_CONST(KEY_PRINT)
XM_CURSES_CONST(KEY_LL)
XM_CURSES_CONST(KEY_A1)
XM_CURSES_CONST(KEY_A3)
XM_CURSES_CONST(KEY_B2)
XM_CURSES_CONST(KEY_C1)
XM_CURSES_CONST(KEY_C3)
XM_CURSES_CONST(KEY_BTAB)
XM_CURSES_CONST(KEY_BEG)
XM_CURSES_CONST(KEY_CANCEL)
XM_CURSES_CONST(KEY_CLOSE)
XM_CURSES_CONST(KEY_COMMAND)
XM_CURSES_CONST(KEY_COPY)
XM_CURSES_CONST(KEY_CREATE)
XM_CURSES_CONST(KEY_END)
XM_CURSES_CONST(KEY_EXIT)
XM_CURSES_CONST(KEY_FIND)
XM_CURSES_CONST(KEY_HELP)
XM_CURSES_CONST(KEY_MARK)
XM_CURSES_CONST(KEY_MESSAGE)
#ifdef PDCURSES
// https://github.com/xmake-io/xmake/issues/1610#issuecomment-971149885
XM_CURSES_CONST(KEY_C2)
XM_CURSES_CONST(KEY_A2)
XM_CURSES_CONST(KEY_B1)
XM_CURSES_CONST(KEY_B3)
#endif
#if !defined(XCURSES)
# ifndef NOMOUSE
XM_CURSES_CONST(KEY_MOUSE)
# endif
#endif
XM_CURSES_CONST(KEY_MOVE)
XM_CURSES_CONST(KEY_NEXT)
XM_CURSES_CONST(KEY_OPEN)
XM_CURSES_CONST(KEY_OPTIONS)
XM_CURSES_CONST(KEY_PREVIOUS)
XM_CURSES_CONST(KEY_REDO)
XM_CURSES_CONST(KEY_REFERENCE)
XM_CURSES_CONST(KEY_REFRESH)
XM_CURSES_CONST(KEY_REPLACE)
XM_CURSES_CONST(KEY_RESIZE)
XM_CURSES_CONST(KEY_RESTART)
XM_CURSES_CONST(KEY_RESUME)
XM_CURSES_CONST(KEY_SAVE)
XM_CURSES_CONST(KEY_SBEG)
XM_CURSES_CONST(KEY_SCANCEL)
XM_CURSES_CONST(KEY_SCOMMAND)
XM_CURSES_CONST(KEY_SCOPY)
XM_CURSES_CONST(KEY_SCREATE)
XM_CURSES_CONST(KEY_SDC)
XM_CURSES_CONST(KEY_SDL)
XM_CURSES_CONST(KEY_SELECT)
XM_CURSES_CONST(KEY_SEND)
XM_CURSES_CONST(KEY_SEOL)
XM_CURSES_CONST(KEY_SEXIT)
XM_CURSES_CONST(KEY_SFIND)
XM_CURSES_CONST(KEY_SHELP)
XM_CURSES_CONST(KEY_SHOME)
XM_CURSES_CONST(KEY_SIC)
XM_CURSES_CONST(KEY_SLEFT)
XM_CURSES_CONST(KEY_SMESSAGE)
XM_CURSES_CONST(KEY_SMOVE)
XM_CURSES_CONST(KEY_SNEXT)
XM_CURSES_CONST(KEY_SOPTIONS)
XM_CURSES_CONST(KEY_SPREVIOUS)
XM_CURSES_CONST(KEY_SPRINT)
XM_CURSES_CONST(KEY_SREDO)
XM_CURSES_CONST(KEY_SREPLACE)
XM_CURSES_CONST(KEY_SRIGHT)
XM_CURSES_CONST(KEY_SRSUME)
XM_CURSES_CONST(KEY_SSAVE)
XM_CURSES_CONST(KEY_SSUSPEND)
XM_CURSES_CONST(KEY_SUNDO)
XM_CURSES_CONST(KEY_SUSPEND)
XM_CURSES_CONST(KEY_UNDO)
// KEY_Fx 0 <= x <= 63
XM_CURSES_CONST(KEY_F0)
XM_CURSES_CONST2(KEY_F1, KEY_F(1))
XM_CURSES_CONST2(KEY_F2, KEY_F(2))
XM_CURSES_CONST2(KEY_F3, KEY_F(3))
XM_CURSES_CONST2(KEY_F4, KEY_F(4))
XM_CURSES_CONST2(KEY_F5, KEY_F(5))
XM_CURSES_CONST2(KEY_F6, KEY_F(6))
XM_CURSES_CONST2(KEY_F7, KEY_F(7))
XM_CURSES_CONST2(KEY_F8, KEY_F(8))
XM_CURSES_CONST2(KEY_F9, KEY_F(9))
XM_CURSES_CONST2(KEY_F10, KEY_F(10))
XM_CURSES_CONST2(KEY_F11, KEY_F(11))
XM_CURSES_CONST2(KEY_F12, KEY_F(12))
#if !defined(XCURSES)
# ifndef NOMOUSE
// mouse constants
XM_CURSES_CONST(BUTTON1_RELEASED)
XM_CURSES_CONST(BUTTON1_PRESSED)
XM_CURSES_CONST(BUTTON1_CLICKED)
XM_CURSES_CONST(BUTTON1_DOUBLE_CLICKED)
XM_CURSES_CONST(BUTTON1_TRIPLE_CLICKED)
XM_CURSES_CONST(BUTTON2_RELEASED)
XM_CURSES_CONST(BUTTON2_PRESSED)
XM_CURSES_CONST(BUTTON2_CLICKED)
XM_CURSES_CONST(BUTTON2_DOUBLE_CLICKED)
XM_CURSES_CONST(BUTTON2_TRIPLE_CLICKED)
XM_CURSES_CONST(BUTTON3_RELEASED)
XM_CURSES_CONST(BUTTON3_PRESSED)
XM_CURSES_CONST(BUTTON3_CLICKED)
XM_CURSES_CONST(BUTTON3_DOUBLE_CLICKED)
XM_CURSES_CONST(BUTTON3_TRIPLE_CLICKED)
XM_CURSES_CONST(BUTTON4_RELEASED)
XM_CURSES_CONST(BUTTON4_PRESSED)
XM_CURSES_CONST(BUTTON4_CLICKED)
XM_CURSES_CONST(BUTTON4_DOUBLE_CLICKED)
XM_CURSES_CONST(BUTTON4_TRIPLE_CLICKED)
XM_CURSES_CONST(BUTTON_CTRL)
XM_CURSES_CONST(BUTTON_SHIFT)
XM_CURSES_CONST(BUTTON_ALT)
XM_CURSES_CONST(REPORT_MOUSE_POSITION)
XM_CURSES_CONST(ALL_MOUSE_EVENTS)
# if NCURSES_MOUSE_VERSION > 1
XM_CURSES_CONST(BUTTON5_RELEASED)
XM_CURSES_CONST(BUTTON5_PRESSED)
XM_CURSES_CONST(BUTTON5_CLICKED)
XM_CURSES_CONST(BUTTON5_DOUBLE_CLICKED)
XM_CURSES_CONST(BUTTON5_TRIPLE_CLICKED)
# endif
# endif
#endif
}
// init curses
static int xm_curses_initscr(lua_State* lua)
{
WINDOW* w = initscr();
if (!w) return 0;
xm_curses_window_new(lua, w);
#if defined(NCURSES_VERSION)
// ESCDELAY = 0;
set_escdelay(0);
#endif
lua_pushstring(lua, XM_CURSES_STDSCR);
lua_pushvalue(lua, -2);
lua_rawset(lua, LUA_REGISTRYINDEX);
xm_curses_register_constants(lua);
#ifndef PDCURSES
atexit(xm_curses_cleanup);
#endif
return 1;
}
static int xm_curses_endwin(lua_State* lua)
{
endwin();
#ifdef XCURSES
XCursesExit();
exit(0);
#endif
return 0;
}
static int xm_curses_stdscr(lua_State* lua)
{
lua_pushstring(lua, XM_CURSES_STDSCR);
lua_rawget(lua, LUA_REGISTRYINDEX);
return 1;
}
#if !defined(XCURSES) && !defined(NOMOUSE)
static int xm_curses_getmouse(lua_State* lua)
{
MEVENT e;
if (getmouse(&e) == OK)
{
lua_pushinteger(lua, e.bstate);
lua_pushinteger(lua, e.x);
lua_pushinteger(lua, e.y);
lua_pushinteger(lua, e.z);
lua_pushinteger(lua, e.id);
return 5;
}
lua_pushnil(lua);
return 1;
}
static int xm_curses_mousemask(lua_State* lua)
{
mmask_t m = luaL_checkint(lua, 1);
mmask_t om;
m = mousemask(m, &om);
lua_pushinteger(lua, m);
lua_pushinteger(lua, om);
return 2;
}
#endif
static int xm_curses_init_pair(lua_State* lua)
{
short pair = luaL_checkint(lua, 1);
short f = luaL_checkint(lua, 2);
short b = luaL_checkint(lua, 3);
lua_pushboolean(lua, XM_CURSES_OK(init_pair(pair, f, b)));
return 1;
}
static int xm_curses_COLOR_PAIR(lua_State* lua)
{
int n = luaL_checkint(lua, 1);
lua_pushnumber(lua, COLOR_PAIR(n));
return 1;
}
static int xm_curses_curs_set(lua_State* lua)
{
int vis = luaL_checkint(lua, 1);
int state = curs_set(vis);
if (state == ERR)
return 0;
lua_pushnumber(lua, state);
return 1;
}
static int xm_curses_napms(lua_State* lua)
{
int ms = luaL_checkint(lua, 1);
lua_pushboolean(lua, XM_CURSES_OK(napms(ms)));
return 1;
}
static int xm_curses_cbreak(lua_State* lua)
{
if (lua_isnoneornil(lua, 1) || lua_toboolean(lua, 1))
lua_pushboolean(lua, XM_CURSES_OK(cbreak()));
else
lua_pushboolean(lua, XM_CURSES_OK(nocbreak()));
return 1;
}
static int xm_curses_echo(lua_State* lua)
{
if (lua_isnoneornil(lua, 1) || lua_toboolean(lua, 1))
lua_pushboolean(lua, XM_CURSES_OK(echo()));
else
lua_pushboolean(lua, XM_CURSES_OK(noecho()));
return 1;
}
static int xm_curses_nl(lua_State* lua)
{
if (lua_isnoneornil(lua, 1) || lua_toboolean(lua, 1))
lua_pushboolean(lua, XM_CURSES_OK(nl()));
else
lua_pushboolean(lua, XM_CURSES_OK(nonl()));
return 1;
}
static int xm_curses_newpad(lua_State* lua)
{
int nlines = luaL_checkint(lua, 1);
int ncols = luaL_checkint(lua, 2);
xm_curses_window_new(lua, newpad(nlines, ncols));
return 1;
}
XM_CURSES_NUMBER2(COLS, COLS)
XM_CURSES_NUMBER2(LINES, LINES)
XM_CURSES_BOOL(isendwin)
XM_CURSES_BOOLOK(start_color)
XM_CURSES_BOOL(has_colors)
XM_CURSES_BOOLOK(doupdate)
XM_CURSES_WINDOW_BOOLOK(wclear)
XM_CURSES_WINDOW_BOOLOK(wnoutrefresh)
/* //////////////////////////////////////////////////////////////////////////////////////
* globals
*/
static const luaL_Reg g_window_functions[] =
{
{ "close", xm_curses_window_delwin },
{ "keypad", xm_curses_window_keypad },
{ "meta", xm_curses_window_meta },
{ "nodelay", xm_curses_window_nodelay },
{ "leaveok", xm_curses_window_leaveok },
{ "move", xm_curses_window_move },
{ "clear", xm_curses_window_wclear },
{ "noutrefresh",xm_curses_window_wnoutrefresh },
{ "attroff", xm_curses_window_attroff },
{ "attron", xm_curses_window_attron },
{ "attrset", xm_curses_window_attrset },
{ "getch", xm_curses_window_getch },
{ "getyx", xm_curses_window_getyx },
{ "getmaxyx", xm_curses_window_getmaxyx },
{ "addch", xm_curses_window_addch },
{ "addstr", xm_curses_window_addnstr },
{ "copy", xm_curses_window_copywin },
{"__gc", xm_curses_window_delwin },
{"__tostring", xm_curses_window_tostring },
{NULL, NULL }
};
static const luaL_Reg g_curses_functions[] =
{
{ "done", xm_curses_endwin },
{ "isdone", xm_curses_isendwin },
{ "main_window", xm_curses_stdscr },
{ "columns", xm_curses_COLS },
{ "lines", xm_curses_LINES },
{ "start_color", xm_curses_start_color },
{ "has_colors", xm_curses_has_colors },
{ "init_pair", xm_curses_init_pair },
{ "color_pair", xm_curses_COLOR_PAIR },
{ "napms", xm_curses_napms },
{ "cursor_set", xm_curses_curs_set },
{ "new_pad", xm_curses_newpad },
{ "doupdate", xm_curses_doupdate },
{ "cbreak", xm_curses_cbreak },
{ "echo", xm_curses_echo },
{ "nl", xm_curses_nl },
#if !defined(XCURSES)
#ifndef NOMOUSE
{ "mousemask", xm_curses_mousemask },
{ "getmouse", xm_curses_getmouse },
#endif
#endif
{NULL, NULL}
};
/* //////////////////////////////////////////////////////////////////////////////////////
* implementations
*/
int xm_lua_curses_register(lua_State* lua, const char* module)
{
// create new metatable for window objects
luaL_newmetatable(lua, XM_CURSES_WINDOW);
lua_pushliteral(lua, "__index");
lua_pushvalue(lua, -2); /* push metatable */
lua_rawset(lua, -3); /* metatable.__index = metatable */
luaL_setfuncs(lua, g_window_functions, 0);
lua_pop(lua, 1); /* remove metatable from stack */
// create global table with curses methods/variables/constants
lua_newtable(lua);
luaL_setfuncs(lua, g_curses_functions, 0);
// add curses.init()
lua_pushstring(lua, "init");
lua_pushvalue(lua, -2);
lua_pushcclosure(lua, xm_curses_initscr, 1);
lua_settable(lua, -3);
// register global curses module
lua_setglobal(lua, module);
/* since version 5.4, the ncurses library decides how to interpret non-ASCII data using the nl_langinfo function.
* that means that you have to call setlocale() in the application and encode Unicode strings using one of the system’s available encodings.
*
* and we need to link libncurses_window.so for drawing vline, hline characters
*/
#if defined(NCURSES_VERSION)
setlocale(LC_ALL, "");
#endif
return 1;
}
#endif
|
0 | repos/xmake/core/src/xmake | repos/xmake/core/src/xmake/path/relative.c | /*!A cross-platform build utility based on Lua
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright (C) 2015-present, TBOOX Open Source Group.
*
* @author ruki
* @file relative.c
*
*/
/* //////////////////////////////////////////////////////////////////////////////////////
* trace
*/
#define TB_TRACE_MODULE_NAME "relative"
#define TB_TRACE_MODULE_DEBUG (0)
/* //////////////////////////////////////////////////////////////////////////////////////
* includes
*/
#include "prefix.h"
/* //////////////////////////////////////////////////////////////////////////////////////
* implementation
*/
tb_int_t xm_path_relative(lua_State* lua)
{
// check
tb_assert_and_check_return_val(lua, 0);
// get the path
tb_char_t const* path = luaL_checkstring(lua, 1);
tb_check_return_val(path, 0);
// get the root
tb_char_t const* root = luaL_optstring(lua, 2, tb_null);
// path:relative(root)
tb_char_t data[TB_PATH_MAXN];
lua_pushstring(lua, tb_path_relative_to(root, path, data, sizeof(data) - 1));
return 1;
}
|
0 | repos/xmake/core/src/xmake | repos/xmake/core/src/xmake/path/prefix.h | /*!A cross-platform build utility based on Lua
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright (C) 2015-present, TBOOX Open Source Group.
*
* @author ruki
* @file prefix.h
*
*/
#ifndef XM_PATH_PREFIX_H
#define XM_PATH_PREFIX_H
/* //////////////////////////////////////////////////////////////////////////////////////
* includes
*/
#include "../prefix.h"
#endif
|
0 | repos/xmake/core/src/xmake | repos/xmake/core/src/xmake/path/directory.c | /*!A cross-platform build utility based on Lua
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright (C) 2015-present, TBOOX Open Source Group.
*
* @author ruki
* @file directory.c
*
*/
/* //////////////////////////////////////////////////////////////////////////////////////
* trace
*/
#define TB_TRACE_MODULE_NAME "directory"
#define TB_TRACE_MODULE_DEBUG (0)
/* //////////////////////////////////////////////////////////////////////////////////////
* includes
*/
#include "prefix.h"
/* //////////////////////////////////////////////////////////////////////////////////////
* implementation
*/
tb_int_t xm_path_directory(lua_State* lua)
{
// check
tb_assert_and_check_return_val(lua, 0);
// get the path
tb_char_t const* path = luaL_checkstring(lua, 1);
tb_check_return_val(path, 0);
// do path:directory()
tb_char_t data[TB_PATH_MAXN];
tb_char_t const* dir = tb_path_directory(path, data, sizeof(data));
if (dir) lua_pushstring(lua, dir);
else lua_pushnil(lua);
return 1;
}
|
0 | repos/xmake/core/src/xmake | repos/xmake/core/src/xmake/path/translate.c | /*!A cross-platform build utility based on Lua
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright (C) 2015-present, TBOOX Open Source Group.
*
* @author ruki
* @file translate.c
*
*/
/* //////////////////////////////////////////////////////////////////////////////////////
* trace
*/
#define TB_TRACE_MODULE_NAME "translate"
#define TB_TRACE_MODULE_DEBUG (0)
/* //////////////////////////////////////////////////////////////////////////////////////
* includes
*/
#include "prefix.h"
/* //////////////////////////////////////////////////////////////////////////////////////
* implementation
*/
tb_int_t xm_path_translate(lua_State* lua)
{
// check
tb_assert_and_check_return_val(lua, 0);
// get the path
size_t path_size = 0;
tb_char_t const* path = luaL_checklstring(lua, 1, &path_size);
tb_check_return_val(path, 0);
// get the option argument, e.g. {normalize = true}
tb_bool_t normalize = tb_false;
if (lua_istable(lua, 2))
{
lua_pushstring(lua, "normalize");
lua_gettable(lua, 2);
if (lua_toboolean(lua, -1))
normalize = tb_true;
lua_pop(lua, 1);
}
// do path:translate()
tb_char_t data[TB_PATH_MAXN];
tb_size_t size = tb_path_translate_to(path, (tb_size_t)path_size, data, sizeof(data), normalize);
if (size) lua_pushlstring(lua, data, (size_t)size);
else lua_pushnil(lua);
return 1;
}
|
0 | repos/xmake/core/src/xmake | repos/xmake/core/src/xmake/path/absolute.c | /*!A cross-platform build utility based on Lua
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright (C) 2015-present, TBOOX Open Source Group.
*
* @author ruki
* @file absolute.c
*
*/
/* //////////////////////////////////////////////////////////////////////////////////////
* trace
*/
#define TB_TRACE_MODULE_NAME "absolute"
#define TB_TRACE_MODULE_DEBUG (0)
/* //////////////////////////////////////////////////////////////////////////////////////
* includes
*/
#include "prefix.h"
/* //////////////////////////////////////////////////////////////////////////////////////
* implementation
*/
tb_int_t xm_path_absolute(lua_State* lua)
{
// check
tb_assert_and_check_return_val(lua, 0);
// get the path
tb_char_t const* path = luaL_checkstring(lua, 1);
tb_check_return_val(path, 0);
// get the root
tb_char_t const* root = luaL_optstring(lua, 2, tb_null);
// do path:absolute(root)
tb_char_t data[TB_PATH_MAXN];
lua_pushstring(lua, tb_path_absolute_to(root, path, data, sizeof(data) - 1));
return 1;
}
|
0 | repos/xmake/core/src/xmake | repos/xmake/core/src/xmake/path/is_absolute.c | /*!A cross-platform build utility based on Lua
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright (C) 2015-present, TBOOX Open Source Group.
*
* @author ruki
* @file is_absolute.c
*
*/
/* //////////////////////////////////////////////////////////////////////////////////////
* trace
*/
#define TB_TRACE_MODULE_NAME "is_absolute"
#define TB_TRACE_MODULE_DEBUG (0)
/* //////////////////////////////////////////////////////////////////////////////////////
* includes
*/
#include "prefix.h"
/* //////////////////////////////////////////////////////////////////////////////////////
* implementation
*/
tb_int_t xm_path_is_absolute(lua_State* lua)
{
// check
tb_assert_and_check_return_val(lua, 0);
// get the path
tb_char_t const* path = luaL_checkstring(lua, 1);
tb_check_return_val(path, 0);
// path:is_absolute()
lua_pushboolean(lua, tb_path_is_absolute(path));
return 1;
}
|
0 | repos/xmake/core/src/xmake | repos/xmake/core/src/xmake/package/loadxmi.c | /*!A cross-platform build utility based on Lua
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright (C) 2015-present, TBOOX Open Source Group.
*
* @author ruki
* @file loadxmi.c
*
*/
/* //////////////////////////////////////////////////////////////////////////////////////
* trace
*/
#define TB_TRACE_MODULE_NAME "loadxmi"
#define TB_TRACE_MODULE_DEBUG (0)
/* //////////////////////////////////////////////////////////////////////////////////////
* includes
*/
#include "prefix.h"
#ifdef USE_LUAJIT
# define XMI_USE_LUAJIT
#endif
#include "xmi.h"
/* //////////////////////////////////////////////////////////////////////////////////////
* types
*/
typedef int (*xm_setup_func_t)(xmi_lua_ops_t* ops);
/* //////////////////////////////////////////////////////////////////////////////////////
* implementation
*/
tb_int_t xm_package_loadxmi(lua_State* lua)
{
// check
tb_assert_and_check_return_val(lua, 0);
tb_char_t const* path = luaL_checkstring(lua, 1);
tb_check_return_val(path, 0);
tb_char_t const* name = luaL_checkstring(lua, 2);
tb_check_return_val(name, 0);
// load module library
tb_dynamic_ref_t lib = tb_dynamic_init(path);
if (!lib)
{
lua_pushnil(lua);
lua_pushfstring(lua, "load %s failed", path);
return 2;
}
// get xmiopen_xxx function
lua_CFunction luaopen_func = (lua_CFunction)tb_dynamic_func(lib, name);
if (!luaopen_func)
{
lua_pushnil(lua);
lua_pushfstring(lua, "cannot get symbol %s failed", name);
return 2;
}
// get xmisetup function
xm_setup_func_t xmisetup_func = (xm_setup_func_t)tb_dynamic_func(lib, "xmisetup");
if (!xmisetup_func)
{
lua_pushnil(lua);
lua_pushfstring(lua, "cannot get symbol xmisetup failed");
return 2;
}
// setup lua interfaces
static xmi_lua_ops_t s_luaops = {0};
static tb_bool_t s_luaops_inited = tb_false;
if (!s_luaops_inited)
{
// get functions
#ifdef XMI_USE_LUAJIT
s_luaops._lua_newuserdata = &lua_newuserdata;
#else
s_luaops._lua_getglobal = &lua_getglobal;
s_luaops._lua_geti = &lua_geti;
s_luaops._lua_rawgetp = &lua_rawgetp;
s_luaops._lua_getiuservalue = &lua_getiuservalue;
s_luaops._lua_newuserdatauv = &lua_newuserdatauv;
#endif
s_luaops._lua_gettable = &lua_gettable;
s_luaops._lua_getfield = &lua_getfield;
s_luaops._lua_rawget = &lua_rawget;
s_luaops._lua_rawgeti = &lua_rawgeti;
s_luaops._lua_createtable = &lua_createtable;
s_luaops._lua_getmetatable = &lua_getmetatable;
// set functions
#ifndef XMI_USE_LUAJIT
s_luaops._lua_setglobal = &lua_setglobal;
s_luaops._lua_seti = &lua_seti;
s_luaops._lua_rawsetp = &lua_rawsetp;
s_luaops._lua_setiuservalue = &lua_setiuservalue;
#endif
s_luaops._lua_settable = &lua_settable;
s_luaops._lua_setfield = &lua_setfield;
s_luaops._lua_rawset = &lua_rawset;
s_luaops._lua_rawseti = &lua_rawseti;
s_luaops._lua_setmetatable = &lua_setmetatable;
// access functions
s_luaops._lua_isnumber = &lua_isnumber;
s_luaops._lua_isstring = &lua_isstring;
s_luaops._lua_iscfunction = &lua_iscfunction;
s_luaops._lua_isuserdata = &lua_isuserdata;
s_luaops._lua_type = &lua_type;
s_luaops._lua_typename = &lua_typename;
#ifndef XMI_USE_LUAJIT
s_luaops._lua_isinteger = &lua_isinteger;
#endif
s_luaops._lua_tonumberx = &lua_tonumberx;
s_luaops._lua_tointegerx = &lua_tointegerx;
s_luaops._lua_toboolean = &lua_toboolean;
s_luaops._lua_tolstring = &lua_tolstring;
s_luaops._lua_tocfunction = &lua_tocfunction;
s_luaops._lua_touserdata = &lua_touserdata;
s_luaops._lua_tothread = &lua_tothread;
s_luaops._lua_topointer = &lua_topointer;
#ifndef XMI_USE_LUAJIT
s_luaops._lua_rawlen = &lua_rawlen;
#endif
// push functions
s_luaops._lua_pushnil = &lua_pushnil;
s_luaops._lua_pushinteger = &lua_pushinteger;
s_luaops._lua_pushboolean = &lua_pushboolean;
s_luaops._lua_pushnumber = &lua_pushnumber;
s_luaops._lua_pushlstring = &lua_pushlstring;
s_luaops._lua_pushstring = &lua_pushstring;
s_luaops._lua_pushvfstring = &lua_pushvfstring;
s_luaops._lua_pushfstring = &lua_pushfstring;
s_luaops._lua_pushcclosure = &lua_pushcclosure;
s_luaops._lua_pushlightuserdata = &lua_pushlightuserdata;
s_luaops._lua_pushthread = &lua_pushthread;
// stack functions
#ifdef XMI_USE_LUAJIT
s_luaops._lua_insert = &lua_insert;
s_luaops._lua_remove = &lua_remove;
s_luaops._lua_replace = &lua_replace;
#else
s_luaops._lua_absindex = &lua_absindex;
s_luaops._lua_rotate = &lua_rotate;
#endif
s_luaops._lua_gettop = &lua_gettop;
s_luaops._lua_settop = &lua_settop;
s_luaops._lua_pushvalue = &lua_pushvalue;
s_luaops._lua_copy = &lua_copy;
s_luaops._lua_checkstack = &lua_checkstack;
s_luaops._lua_xmove = &lua_xmove;
// miscellaneous functions
s_luaops._lua_error = &lua_error;
s_luaops._lua_next = &lua_next;
s_luaops._lua_concat = &lua_concat;
s_luaops._lua_getallocf = &lua_getallocf;
s_luaops._lua_setallocf = &lua_setallocf;
#ifndef XMI_USE_LUAJIT
s_luaops._lua_len = &lua_len;
s_luaops._lua_toclose = &lua_toclose;
s_luaops._lua_closeslot = &lua_closeslot;
s_luaops._lua_stringtonumber = &lua_stringtonumber;
#endif
// 'load' and 'call' functions
#ifdef XMI_USE_LUAJIT
s_luaops._lua_call = &lua_call;
s_luaops._lua_pcall = &lua_pcall;
#else
s_luaops._lua_callk = &lua_callk;
s_luaops._lua_pcallk = &lua_pcallk;
#endif
s_luaops._lua_load = &lua_load;
s_luaops._lua_dump = &lua_dump;
// luaL functions
#ifndef XMI_USE_LUAJIT
s_luaops._luaL_tolstring = &luaL_tolstring;
s_luaops._luaL_typeerror = &luaL_typeerror;
#endif
s_luaops._luaL_getmetafield = &luaL_getmetafield;
s_luaops._luaL_callmeta = &luaL_callmeta;
s_luaops._luaL_argerror = &luaL_argerror;
s_luaops._luaL_checklstring = &luaL_checklstring;
s_luaops._luaL_optlstring = &luaL_optlstring;
s_luaops._luaL_checknumber = &luaL_checknumber;
s_luaops._luaL_optnumber = &luaL_optnumber;
s_luaops._luaL_checkinteger = &luaL_checkinteger;
s_luaops._luaL_optinteger = &luaL_optinteger;
s_luaops._luaL_checkstack = &luaL_checkstack;
s_luaops._luaL_checktype = &luaL_checktype;
s_luaops._luaL_checkany = &luaL_checkany;
s_luaops._luaL_newmetatable = &luaL_newmetatable;
s_luaops._luaL_testudata = &luaL_testudata;
s_luaops._luaL_checkudata = &luaL_checkudata;
s_luaops._luaL_where = &luaL_where;
s_luaops._luaL_error = &luaL_error;
s_luaops._luaL_checkoption = &luaL_checkoption;
s_luaops._luaL_fileresult = &luaL_fileresult;
s_luaops._luaL_execresult = &luaL_execresult;
s_luaops._luaL_setfuncs = &luaL_setfuncs;
s_luaops_inited = tb_true;
}
xmisetup_func(&s_luaops);
// load module
lua_pushcfunction(lua, luaopen_func);
return 1;
}
|
0 | repos/xmake/core/src/xmake | repos/xmake/core/src/xmake/package/prefix.h | /*!A cross-platform build utility based on Lua
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright (C) 2015-present, TBOOX Open Source Group.
*
* @author ruki
* @file prefix.h
*
*/
#ifndef XM_PACKAGE_PREFIX_H
#define XM_PACKAGE_PREFIX_H
/* //////////////////////////////////////////////////////////////////////////////////////
* includes
*/
#include "../prefix.h"
#endif
|
0 | repos/xmake | repos/xmake/scripts/srcenv.ps1 | $xmake_root = (Split-Path $PSScriptRoot -Parent)
$env:PATH = "$xmake_root\core\build;$pwd;$env:PATH"
$env:XMAKE_PROGRAM_FILE = "$xmake_root\core\build\xmake.exe"
$env:XMAKE_PROGRAM_DIR = "$xmake_root\xmake"
Set-Location "$xmake_root"
Start-Process powershell |
0 | repos/xmake | repos/xmake/scripts/get.ps1 | #!/usr/bin/env pwsh
#Requires -version 5
# xmake getter
# usage: (in powershell)
# Invoke-Expression (Invoke-Webrequest <my location> -UseBasicParsing).Content
param (
[string]$version = "master",
[string]$installdir = ""
)
& {
$LastRelease = "v2.9.4"
$ErrorActionPreference = 'Stop'
function writeErrorTip($msg) {
Write-Host $msg -BackgroundColor Red -ForegroundColor White
}
if (-not $env:CI) {
$logo = @(
' _ '
' __ ___ __ __ __ _| | ______ '
' \ \/ / | \/ |/ _ | |/ / __ \ '
' > < | \__/ | /_| | < ___/ '
' /_/\_\_|_| |_|\__ \|_|\_\____| getter '
' '
' ')
Write-Host $([string]::Join("`n", $logo)) -ForegroundColor Green
}
if ($IsLinux -or $IsMacOS) {
writeErrorTip 'Install on *nix is not supported, try '
writeErrorTip '(Use curl) "curl -fsSL https://xmake.io/shget.text | bash"'
writeErrorTip 'or'
writeErrorTip '(Use wget) "wget https://xmake.io/shget.text -O - | bash"'
throw 'Unsupported platform'
}
$temppath = ([System.IO.Path]::GetTempPath(), $env:TMP, $env:TEMP, "$(Get-Location)" -ne $null)[0]
[Net.ServicePointManager]::SecurityProtocol = "tls12, tls11, tls"
if ($null -eq $installdir -or $installdir -match '^\s*$') {
$installdir = & {
# Install to old xmake path
$oldXmake = Get-Command xmake -CommandType Application -ErrorAction SilentlyContinue
if ($oldXmake) {
return Split-Path $oldXmake.Path -Parent
}
if ($HOME) {
return Join-Path $HOME 'xmake'
}
if ($env:APPDATA) {
return Join-Path $env:APPDATA 'xmake'
}
if ($env:ProgramFiles) {
return Join-Path $env:ProgramFiles 'xmake'
}
return 'C:\xmake'
}
}
$installdir = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($installdir)
if ($null -eq $version -or $version -match '^\s*$') {
$v = 'master'
} else {
$v = $version.Trim()
if ($v.Contains('.')) {
$v = [version]::Parse($version)
$v = New-Object -TypeName version -ArgumentList $v.Major, $v.Minor, $v.Build
}
}
function checkTempAccess {
$outfile = Join-Path $temppath "$pid.tmp"
try {
Write-Output $pid | Out-File -FilePath $outfile
Remove-Item $outfile
} catch {
writeErrorTip 'Cannot write to temp path'
writeErrorTip 'Please set environment var "TMP" to another path'
throw
}
}
function xmakeInstall {
$outfile = Join-Path $temppath "$pid-xmake-installer.exe"
$x64arch = @('AMD64', 'IA64')
$arch = if ($env:PROCESSOR_ARCHITECTURE -in $x64arch -or $env:PROCESSOR_ARCHITEW6432 -in $x64arch) { 'x64' } else { 'x86' }
$winarch = if ($env:PROCESSOR_ARCHITECTURE -in $x64arch -or $env:PROCESSOR_ARCHITEW6432 -in $x64arch) { 'win64' } else { 'win32' }
if ($env:PROCESSOR_ARCHITECTURE -eq 'ARM64') {
Write-Host "Unsupported host architecture detected: ARM64."
}
$url = if ($v -is [version]) {
"https://github.com/xmake-io/xmake/releases/download/v$v/xmake-v$v.$winarch.exe"
} else {
"https://github.com/xmake-io/xmake/releases/download/$LastRelease/xmake-$v.$winarch.exe"
}
Write-Host "Start downloading $url .."
try {
Invoke-Webrequest $url -OutFile $outfile -UseBasicParsing
} catch {
writeErrorTip 'Download failed!'
writeErrorTip 'Check your network or... the news of S3 break'
throw
}
Write-Host 'Start installation... Hope your antivirus doesn''t trouble'
Write-Host "Install to $installdir"
try {
$adminflag = "/NOADMIN "
try {
$tempfolder = New-Item "$installdir-$PID-temp" -ItemType Directory
Remove-Item $tempfolder.FullName
} catch {
$adminflag = ""
}
Start-Process -FilePath $outfile -ArgumentList "$adminflag/S /D=$installdir" -Wait
} catch {
writeErrorTip 'Install failed!'
writeErrorTip 'Close your antivirus then try again'
throw
} finally {
Remove-Item $outfile -ErrorAction SilentlyContinue
}
Write-Host 'Adding to PATH... almost done'
$env:Path += ";$installdir"
try {
xmake --version
} catch {
writeErrorTip 'Everything is showing installation has finished'
writeErrorTip 'But xmake could not run... Why?'
throw
}
}
function registerTabCompletion {
# TODO: add --global --user choice
Write-Host "Tab completion service"
try {
xmake update --integrate
} catch {
writeErrorTip "Failed to register tab completion!"
writeErrorTip 'Please try "xmake update --integrate" to register manually.'
return
}
Write-Host "Tab completion installed"
}
checkTempAccess
xmakeInstall
if (-not $env:CI) {
registerTabCompletion
} else {
Write-Host "Tab completion registration has been skipped for CI"
}
}
|
0 | repos/xmake | repos/xmake/scripts/xrepo.bat | @set "XMAKE_ROOTDIR=%~dp0"
@if not defined XMAKE_PROGRAM_FILE (
@set "XMAKE_PROGRAM_FILE=%XMAKE_ROOTDIR%xmake.exe"
)
@if [%1]==[env] (
if [%2]==[quit] (
if defined XMAKE_PROMPT_BACKUP (
call %XMAKE_ENV_BACKUP%
setlocal EnableDelayedExpansion
if !errorlevel! neq 0 exit /B !errorlevel!
endlocal
set "PROMPT=%XMAKE_PROMPT_BACKUP%"
set XMAKE_ENV_BACKUP=
set XMAKE_PROMPT_BACKUP=
)
goto :ENDXREPO
)
if [%2]==[shell] (
if defined XMAKE_PROMPT_BACKUP (
call %XMAKE_ENV_BACKUP%
setlocal EnableDelayedExpansion
if !errorlevel! neq 0 exit /B !errorlevel!
"%XMAKE_PROGRAM_FILE%" lua private.xrepo.action.env.info config
if !errorlevel! neq 0 (
exit /B !errorlevel!
)
@"%XMAKE_PROGRAM_FILE%" lua --quiet private.xrepo.action.env.info prompt 1>nul
if !errorlevel! neq 0 (
echo error: xmake.lua not found^^!
exit /B !errorlevel!
)
endlocal
set "PROMPT=%XMAKE_PROMPT_BACKUP%"
set XMAKE_ENV_BACKUP=
set XMAKE_PROMPT_BACKUP=
echo Please rerun `xrepo env shell` to enter the environment.
exit /B 1
) else (
setlocal EnableDelayedExpansion
"%XMAKE_PROGRAM_FILE%" lua private.xrepo.action.env.info config
if !errorlevel! neq 0 (
exit /B !errorlevel!
)
@"%XMAKE_PROGRAM_FILE%" lua --quiet private.xrepo.action.env | findstr . && (
echo error: corrupt xmake.lua detected in the current directory^^!
exit /B 1
)
@"%XMAKE_PROGRAM_FILE%" lua --quiet private.xrepo.action.env.info prompt 1>nul
if !errorlevel! neq 0 (
echo error: xmake.lua not found^^!
exit /B !errorlevel!
)
endlocal
for /f %%i in ('@"%XMAKE_PROGRAM_FILE%" lua --quiet private.xrepo.action.env.info prompt') do @(
@set "PROMPT=%%i %PROMPT%"
)
@set "XMAKE_PROMPT_BACKUP=%PROMPT%"
)
for /f %%i in ('@"%XMAKE_PROGRAM_FILE%" lua private.xrepo.action.env.info envfile') do @(
@set "XMAKE_ENV_BACKUP=%%i.bat"
@"%XMAKE_PROGRAM_FILE%" lua private.xrepo.action.env.info backup.cmd 1>"%%i.bat"
)
for /f %%i in ('@"%XMAKE_PROGRAM_FILE%" lua private.xrepo.action.env.info envfile') do @(
@"%XMAKE_PROGRAM_FILE%" lua private.xrepo.action.env.info script.cmd 1>"%%i.bat"
call "%%i.bat"
)
goto :ENDXREPO
)
set XREPO_BIND_FLAG=
if [%2]==[-b] if [%4]==[shell] (
set XREPO_BIND_FLAG=1
)
if [%2]==[--bind] if [%4]==[shell] (
set XREPO_BIND_FLAG=1
)
if defined XREPO_BIND_FLAG (
set XREPO_BIND_FLAG=
if defined XMAKE_PROMPT_BACKUP (
call %XMAKE_ENV_BACKUP%
setlocal EnableDelayedExpansion
if !errorlevel! neq 0 exit /B !errorlevel!
endlocal
set "PROMPT=%XMAKE_PROMPT_BACKUP%"
set XMAKE_ENV_BACKUP=
set XMAKE_PROMPT_BACKUP=
echo Please rerun `xrepo env %2 %3 shell` to enter the environment.
exit /B 1
) else (
pushd %XMAKE_ROOTDIR%
setlocal EnableDelayedExpansion
%XMAKE_PROGRAM_FILE% lua private.xrepo.action.env.info config %3
if !errorlevel! neq 0 (
popd
exit /B !errorlevel!
)
@%XMAKE_PROGRAM_FILE% lua --quiet private.xrepo.action.env.info prompt %3 1>nul
if !errorlevel! neq 0 (
popd
echo error: environment not found^^!
exit /B !errorlevel!
)
endlocal
for /f %%i in ('@%XMAKE_PROGRAM_FILE% lua --quiet private.xrepo.action.env.info prompt %3') do @(
@set "PROMPT=%%i %PROMPT%"
)
@set "XMAKE_PROMPT_BACKUP=%PROMPT%"
)
for /f %%i in ('@%XMAKE_PROGRAM_FILE% lua private.xrepo.action.env.info envfile %3') do @(
@set "XMAKE_ENV_BACKUP=%%i.bat"
@"%XMAKE_PROGRAM_FILE%" lua --quiet private.xrepo.action.env.info backup.cmd %3 1>"%%i.bat"
)
for /f %%i in ('@%XMAKE_PROGRAM_FILE% lua private.xrepo.action.env.info envfile %3') do @(
@"%XMAKE_PROGRAM_FILE%" lua --quiet private.xrepo.action.env.info script.cmd %3 1>"%%i.bat"
call "%%i.bat"
)
popd
goto :ENDXREPO
)
)
@call "%XMAKE_PROGRAM_FILE%" lua private.xrepo %*
:ENDXREPO
|
0 | repos/xmake | repos/xmake/scripts/xrepo.sh | #!/usr/bin/env bash
BASEDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
if [ -f "$BASEDIR/xmake" ]; then
$BASEDIR/xmake lua private.xrepo "$@"
else
xmake lua private.xrepo "$@"
fi
|
0 | repos/xmake | repos/xmake/scripts/xrepo.ps1 | $script:SCRIPT_PATH = $myinvocation.mycommand.path
$script:BASE_DIR = Split-Path $SCRIPT_PATH -Parent
$Env:XMAKE_PROGRAM_FILE = Join-Path $BASE_DIR xmake.exe
if ($Args.Count -eq 0) {
# No args, just call the underlying xmake executable.
& $Env:XMAKE_PROGRAM_FILE lua private.xrepo;
} else {
$Command = $Args[0];
if (($Command -eq "env") -and ($Args.Count -ge 2)) {
switch ($Args[1]) {
"shell" {
if (-not (Test-Path 'Env:XMAKE_ROOTDIR')) {
$Env:XMAKE_ROOTDIR = $BASE_DIR;
Import-Module "$Env:XMAKE_ROOTDIR\scripts\xrepo-hook.psm1";
Add-XrepoEnvironmentToPrompt;
}
if ((Test-Path 'Env:XMAKE_PROMPT_MODIFIER') -and ($Env:XMAKE_PROMPT_MODIFIER -ne "")) {
Exit-XrepoEnvironment;
}
Enter-XrepoEnvironment $Null;
return;
}
"quit" {
Exit-XrepoEnvironment;
return;
}
{$_ -in "-b", "--bind"} {
if (($Args.Count -ge 4) -and ($Args[3] -eq "shell")) {
if (-not (Test-Path 'Env:XMAKE_ROOTDIR')) {
$Env:XMAKE_ROOTDIR = $BASE_DIR;
Import-Module "$Env:XMAKE_ROOTDIR\scripts\xrepo-hook.psm1";
Add-XrepoEnvironmentToPrompt;
}
if ((Test-Path 'Env:XMAKE_PROMPT_MODIFIER') -and ($Env:XMAKE_PROMPT_MODIFIER -ne "")) {
Exit-XrepoEnvironment;
}
Enter-XrepoEnvironment $Args[2];
return;
}
}
}
}
& $Env:XMAKE_PROGRAM_FILE lua private.xrepo $Args;
}
|
0 | repos/xmake | repos/xmake/scripts/get.sh | #!/usr/bin/env bash
# xmake getter
# usage: bash <(curl -s <my location>) [branch|__local__|__run__] [commit/__install_only__]
set -o pipefail
#-----------------------------------------------------------------------------
# some helper functions
#
raise() {
echo "$@" 1>&2 ; exit 1
}
test_z() {
if test "x${1}" = "x"; then
return 0
fi
return 1
}
test_nz() {
if test "x${1}" != "x"; then
return 0
fi
return 1
}
test_eq() {
if test "x${1}" = "x${2}"; then
return 0
fi
return 1
}
test_nq() {
if test "x${1}" != "x${2}"; then
return 0
fi
return 1
}
#-----------------------------------------------------------------------------
# prepare
#
# print a LOGO!
echo 'xmake, A cross-platform build utility based on Lua. '
echo 'Copyright (C) 2015-present Ruki Wang, tboox.org, xmake.io'
echo ' _ '
echo ' __ ___ __ __ __ _| | ______ '
echo ' \ \/ / | \/ |/ _ | |/ / __ \ '
echo ' > < | \__/ | /_| | < ___/ '
echo ' /_/\_\_|_| |_|\__ \|_|\_\____| '
echo ' by ruki, xmake.io '
echo ' '
echo ' 👉 Manual: https://xmake.io/#/getting_started '
echo ' 🙏 Donate: https://xmake.io/#/sponsor '
echo ' '
# has sudo?
if [ 0 -ne "$(id -u)" ]; then
if sudo --version >/dev/null 2>&1
then
sudoprefix=sudo
else
sudoprefix=
fi
else
export XMAKE_ROOT=y
sudoprefix=
fi
# make tmpdir
if [ -z "$TMPDIR" ]; then
tmpdir=/tmp/.xmake_getter$$
else
tmpdir=$TMPDIR/.xmake_getter$$
fi
if [ -d $tmpdir ]; then
rm -rf $tmpdir
fi
# get make
if gmake --version >/dev/null 2>&1
then
make=gmake
else
make=make
fi
remote_get_content() {
if curl --version >/dev/null 2>&1
then
curl -fSL "$1"
elif wget --version >/dev/null 2>&1 || wget --help >/dev/null 2>&1
then
wget "$1" -O -
fi
}
get_host_speed() {
if [ `uname` == "Darwin" ]; then
ping -c 1 -t 1 $1 2>/dev/null | egrep -o 'time=\d+' | egrep -o "\d+" || echo "65535"
else
ping -c 1 -W 1 $1 2>/dev/null | grep -E -o 'time=[0-9]+' | grep -E -o "[0-9]+" || echo "65535"
fi
}
get_fast_host() {
speed_gitee=$(get_host_speed "gitee.com")
speed_github=$(get_host_speed "github.com")
if [ $speed_gitee -le $speed_github ]; then
echo "gitee.com"
else
echo "github.com"
fi
}
# get branch
branch=__run__
if test_nz "$1"; then
brancharr=($1)
if [ ${#brancharr[@]} -eq 1 ]
then
branch=${brancharr[0]}
fi
echo "Branch: $branch"
fi
# get fasthost and git repository
if test_nq "$branch" "__local__"; then
fasthost=$(get_fast_host)
if test_eq "$fasthost" "gitee.com"; then
gitrepo="https://gitee.com/tboox/xmake.git"
gitrepo_raw="https://gitee.com/tboox/xmake/raw/master"
else
gitrepo="https://github.com/xmake-io/xmake.git"
#gitrepo_raw="https://github.com/xmake-io/xmake/raw/master"
gitrepo_raw="https://fastly.jsdelivr.net/gh/xmake-io/xmake@master"
fi
fi
#-----------------------------------------------------------------------------
# install tools
#
test_tools() {
prog='#include <stdio.h>\nint main(){return 0;}'
{
git --version &&
$make --version &&
{
echo -e "$prog" | cc -xc - -o /dev/null ||
echo -e "$prog" | gcc -xc - -o /dev/null ||
echo -e "$prog" | clang -xc - -o /dev/null ||
echo -e "$prog" | cc -xc -c - -o /dev/null -I/usr/include -I/usr/local/include ||
echo -e "$prog" | gcc -xc -c - -o /dev/null -I/usr/include -I/usr/local/include ||
echo -e "$prog" | clang -xc -c - -o /dev/null -I/usr/include -I/usr/local/include
}
} >/dev/null 2>&1
}
install_tools() {
{ apt --version >/dev/null 2>&1 && $sudoprefix apt install -y git build-essential libreadline-dev; } ||
{ yum --version >/dev/null 2>&1 && $sudoprefix yum install -y git readline-devel bzip2 && $sudoprefix yum groupinstall -y 'Development Tools'; } ||
{ zypper --version >/dev/null 2>&1 && $sudoprefix zypper --non-interactive install git readline-devel && $sudoprefix zypper --non-interactive install -t pattern devel_C_C++; } ||
{ pacman -V >/dev/null 2>&1 && $sudoprefix pacman -S --noconfirm --needed git base-devel ncurses readline; } ||
{ emerge -V >/dev/null 2>&1 && $sudoprefix emerge -atv dev-vcs/git; } ||
{ pkg list-installed >/dev/null 2>&1 && $sudoprefix pkg install -y git getconf build-essential readline; } || # termux
{ pkg help >/dev/null 2>&1 && $sudoprefix pkg install -y git readline ncurses; } || # freebsd
{ nix-env --version >/dev/null 2>&1 && nix-env -i git gcc readline ncurses; } || # nixos
{ apk --version >/dev/null 2>&1 && $sudoprefix apk add git gcc g++ make readline-dev ncurses-dev libc-dev linux-headers; } ||
{ xbps-install --version >/dev/null 2>&1 && $sudoprefix xbps-install -Sy git base-devel; } #void
}
test_tools || { install_tools && test_tools; } || raise "$(echo -e 'Dependencies Installation Fail\nThe getter currently only support these package managers\n\t* apt\n\t* yum\n\t* zypper\n\t* pacman\n\t* portage\n\t* xbps\n Please install following dependencies manually:\n\t* git\n\t* build essential like `make`, `gcc`, etc\n\t* libreadline-dev (readline-devel)')" 1
#-----------------------------------------------------------------------------
# install xmake
#
projectdir=$tmpdir
if test_eq "$branch" "__local__"; then
if [ -d '.git' ]; then
git submodule update --init --recursive
fi
cp -r . $projectdir
elif test_eq "$branch" "__run__"; then
version=$(git ls-remote --tags "$gitrepo" | tail -c 7)
pack=gz
mkdir -p $projectdir
runfile_url="https://fastly.jsdelivr.net/gh/xmake-mirror/xmake-releases@$version/xmake-$version.$pack.run"
echo "downloading $runfile_url .."
remote_get_content "$runfile_url" > $projectdir/xmake.run
if [[ $? != 0 ]]; then
runfile_url="https://github.com/xmake-io/xmake/releases/download/$version/xmake-$version.$pack.run"
echo "downloading $runfile_url .."
remote_get_content "$runfile_url" > $projectdir/xmake.run
fi
sh $projectdir/xmake.run --noexec --quiet --target $projectdir
else
echo "cloning $gitrepo $branch .."
if test_nz "$2"; then
git clone --filter=tree:0 --no-checkout -b "$branch" "$gitrepo" --recurse-submodules $projectdir || raise "clone failed, check your network or branch name"
cd $projectdir || raise 'chdir failed!'
git checkout -qf "$2"
cd - || raise 'chdir failed!'
else
git clone --depth=1 -b "$branch" "$gitrepo" --recurse-submodules $projectdir || raise "clone failed, check your network or branch name"
fi
fi
# do build
if test_nq "$2" "__install_only__"; then
if [ -f "$projectdir/configure" ]; then
cd $projectdir || raise 'chdir failed!'
./configure || raise "configure failed!"
cd - || raise 'chdir failed!'
fi
$make -C $projectdir --no-print-directory || raise "make failed!"
fi
# do install
if test_z "$prefix"; then
prefix=~/.local
fi
if test_nz "$prefix"; then
$make -C $projectdir --no-print-directory install PREFIX="$prefix" || raise "install failed!"
else
$sudoprefix $make -C $projectdir --no-print-directory install || raise "install failed!"
fi
#-----------------------------------------------------------------------------
# install profile
#
install_profile() {
export XMAKE_ROOTDIR="$prefix/bin"
[[ "$PATH" =~ (^|:)"$XMAKE_ROOTDIR"(:|$) ]] || export PATH="$XMAKE_ROOTDIR:$PATH"
xmake --version
xmake update --integrate
}
install_profile
|
0 | repos/xmake | repos/xmake/scripts/srcenv.bat | @echo off
setlocal
set script_dir=%~dp0
set PATH=%script_dir%..\core\build;%cd%;%PATH%
set XMAKE_PROGRAM_DIR=%script_dir%..\xmake
set XMAKE_PROGRAM_FILE=%script_dir%..\core\build\xmake.exe
start cmd /k cd %script_dir%..\
endlocal
|
0 | repos/xmake/scripts | repos/xmake/scripts/termux/build.sh | TERMUX_PKG_HOMEPAGE=http://xmake.io/
TERMUX_PKG_DESCRIPTION="A cross-platform build utility based on Lua"
TERMUX_PKG_LICENSE="GPL-2.0"
TERMUX_PKG_MAINTAINER="Ruki Wang @waruqi"
TERMUX_PKG_VERSION=2.3.1
TERMUX_PKG_REVISION=1
TERMUX_PKG_SRCURL=https://github.com/xmake-io/xmake/releases/download/v${TERMUX_PKG_VERSION}/xmake-v${TERMUX_PKG_VERSION}.tar.gz
TERMUX_PKG_SHA256=c927efad5412c3bdb8bad1be5b1b2ea40a998dff2a252edb443782865b7472b9
TERMUX_PKG_BUILD_IN_SRC=true
TERMUX_PKG_DEPENDS="clang, make, readline"
termux_step_make() {
make build
}
termux_step_make_install() {
make install PREFIX="${TERMUX_PREFIX}"
}
|
0 | repos/xmake/scripts | repos/xmake/scripts/msys/xmake.sh | #!/usr/bin/env bash
BASEDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
if [ -f "$BASEDIR/../share/xmake/xmake.exe" ]; then
$BASEDIR/../share/xmake/xmake.exe "$@"
fi
|
0 | repos/xmake/scripts | repos/xmake/scripts/rpmbuild/0002-pkgconfig-unversioned-lua.patch | diff --git a/core/xmake.sh b/core/xmake.sh
index 2ae2e686b..2b7767b0c 100755
--- a/core/xmake.sh
+++ b/core/xmake.sh
@@ -91,8 +91,8 @@ option_find_lua() {
local ldflags=""
local cflags=""
option "lua"
- cflags=`pkg-config --cflags lua5.4 2>/dev/null`
- ldflags=`pkg-config --libs lua5.4 2>/dev/null`
+ cflags=`pkg-config --cflags lua 2>/dev/null`
+ ldflags=`pkg-config --libs lua 2>/dev/null`
if test_z "${cflags}"; then
cflags="-I/usr/include/lua5.4"
fi
|
0 | repos/xmake/scripts | repos/xmake/scripts/rpmbuild/0001-use-static-libsv-and-tbox.patch | diff --git a/core/src/xmake/xmake.sh b/core/src/xmake/xmake.sh
index dc45ecbca..d0e0d0069 100755
--- a/core/src/xmake/xmake.sh
+++ b/core/src/xmake/xmake.sh
@@ -6,6 +6,8 @@ target "xmake"
# add deps
if has_config "external"; then
+ add_deps "sv"
+ add_deps "tbox"
local libs="lz4 sv tbox"
for lib in $libs; do
if has_config "$lib"; then
diff --git a/core/xmake.sh b/core/xmake.sh
index 2ae2e686b..6ea8c1b69 100755
--- a/core/xmake.sh
+++ b/core/xmake.sh
@@ -214,6 +214,9 @@ if ! has_config "external"; then
includes "src/lz4"
includes "src/sv"
includes "src/tbox"
+else
+ includes "src/sv"
+ includes "src/tbox"
fi
includes "src/xmake"
includes "src/demo"
|
0 | repos/xmake/xmake/modules | repos/xmake/xmake/modules/os/winver.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file winver.lua
--
-- get WINVER from name
--
-- reference: https://msdn.microsoft.com/en-us/library/windows/desktop/aa383745(v=vs.85).aspx
--
function version(name)
-- init values
_g.values = _g.values or
{
nt4 = "0x0400"
, win2k = "0x0500"
, winxp = "0x0501"
, ws03 = "0x0502"
, win6 = "0x0600"
, vista = "0x0600"
, ws08 = "0x0600"
, longhorn = "0x0600"
, win7 = "0x0601"
, win8 = "0x0602"
, winblue = "0x0603"
, win81 = "0x0603"
, win10 = "0x0A00"
}
-- ignore the subname with '_xxx'
name = name:split('_')[1]
-- get value
return _g.values[name]
end
-- get NTDDI_VERSION from name
function ntddi_version(name)
-- init subvalues
_g.subvalues = _g.subvalues or
{
sp1 = "0100"
, sp2 = "0200"
, sp3 = "0300"
, sp4 = "0400"
, th2 = "0001"
, rs1 = "0002"
, rs2 = "0003"
, rs3 = "0004"
, rs4 = "0005"
, rs5 = "0006"
, h1 = "0007"
, vb = "0008"
, nm = "0009"
, fe = "000A"
, co = "000B"
, ni = "000C"
}
-- get subvalue
local subvalue = nil
local subname = name:split('_')[2]
if subname then
subvalue = _g.subvalues[subname]
end
-- get value
local val = version(name)
if val then
val = val .. (subvalue or "0000")
end
return val
end
-- get _WIN32_WINNT from name
function winnt_version(name)
return version(name)
end
-- get _NT_TARGET_VERSION from name
function target_version(name)
return version(name)
end
-- get subsystem version from name
function subsystem(name)
-- ignore the subname with '_xxx'
name = (name or ""):split('_')[1]
-- make defined values
local defvals =
{
nt4 = "4.00"
, win2k = "5.00"
, winxp = "5.01"
, ws03 = "5.02"
, win6 = "6.00"
, vista = "6.00"
, ws08 = "6.00"
, longhorn = "6.00"
, win7 = "6.01"
, win8 = "6.02"
, winblue = "6.03"
, win81 = "6.03"
, win10 = "10.00"
}
return defvals[name] or "10.00"
end
|
0 | repos/xmake/xmake/modules/target/action | repos/xmake/xmake/modules/target/action/uninstall/main.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file main.lua
--
-- imports
import("core.base.option")
import("core.base.hashset")
import("utils.binary.deplibs", {alias = "get_depend_libraries"})
import("private.action.clean.remove_files")
-- we need to get all deplibs, e.g. app -> libfoo.so -> libbar.so ...
-- @see https://github.com/xmake-io/xmake/issues/5325#issuecomment-2242597732
function _get_target_package_deplibs(target, depends, libfiles, binaryfile)
local deplibs = get_depend_libraries(binaryfile, {plat = target:plat(), arch = target:arch()})
local depends_new = hashset.new()
for _, deplib in ipairs(deplibs) do
local libname = path.filename(deplib)
if not depends:has(libname) then
depends:insert(libname)
depends_new:insert(libname)
end
end
for _, libfile in ipairs(libfiles) do
local libname = path.filename(libfile)
if depends_new:has(libname) then
_get_target_package_deplibs(target, depends, libfiles, libfile)
end
end
end
function _get_target_package_libfiles(target, opt)
if option.get("nopkgs") then
return {}
end
local libfiles = {}
local bindir = target:is_plat("windows", "mingw") and target:bindir() or target:libdir()
for _, pkg in ipairs(target:orderpkgs(opt)) do
if pkg:enabled() and pkg:get("libfiles") then
for _, libfile in ipairs(table.wrap(pkg:get("libfiles"))) do
local filename = path.filename(libfile)
if filename:endswith(".dll") or filename:endswith(".so") or filename:find("%.so%.%d+$") or filename:endswith(".dylib") then
table.insert(libfiles, libfile)
end
end
end
end
-- we can only reserve used libraries
if target:is_binary() or target:is_shared() then
local depends = hashset.new()
_get_target_package_deplibs(target, depends, libfiles, target:targetfile())
table.remove_if(libfiles, function (_, libfile) return not depends:has(path.filename(libfile)) end)
end
return libfiles
end
-- remove file with symbols
function _remove_file_with_symbols(filepath)
if os.islink(filepath) then
local filepath_symlink = os.readlink(filepath)
if not path.is_absolute(filepath_symlink) then
filepath_symlink = path.join(path.directory(filepath), filepath_symlink)
end
_remove_file_with_symbols(filepath_symlink)
end
remove_files(filepath, {emptydir = true})
end
-- uninstall files
function _uninstall_files(target)
local _, dstfiles = target:installfiles()
for _, dstfile in ipairs(dstfiles) do
remove_files(dstfile, {emptydir = true})
end
for _, dep in ipairs(target:orderdeps()) do
local _, dstfiles = dep:installfiles(dep:installdir(), {interface = true})
for _, dstfile in ipairs(dstfiles) do
remove_files(dstfile, {emptydir = true})
end
end
end
-- uninstall headers
function _uninstall_headers(target, opt)
local _, dstheaders = target:headerfiles(target:includedir(), {installonly = true})
for _, dstheader in ipairs(dstheaders) do
remove_files(dstheader, {emptydir = true})
end
for _, dep in ipairs(target:orderdeps()) do
local _, dstfiles = dep:headerfiles(dep:includedir(), {installonly = true, interface = true})
for _, dstfile in ipairs(dstfiles) do
remove_files(dstfile, {emptydir = true})
end
end
end
-- uninstall shared libraries
function _uninstall_shared_libraries(target, opt)
local bindir = target:is_plat("windows", "mingw") and target:bindir() or target:libdir()
-- get all dependent shared libraries
local libfiles = {}
for _, dep in ipairs(target:orderdeps()) do
if dep:kind() == "shared" then
local depfile = dep:targetfile()
if os.isfile(depfile) then
table.insert(libfiles, depfile)
end
end
table.join2(libfiles, _get_target_package_libfiles(dep, {interface = true}))
end
table.join2(libfiles, _get_target_package_libfiles(target))
-- deduplicate libfiles, prevent packages using the same libfiles from overwriting each other
libfiles = table.unique(libfiles)
-- do uninstall
for _, libfile in ipairs(libfiles) do
local filename = path.filename(libfile)
local filepath = path.join(bindir, filename)
_remove_file_with_symbols(filepath)
end
end
-- uninstall binary
function _uninstall_binary(target, opt)
local bindir = target:bindir()
remove_files(path.join(bindir, path.filename(target:targetfile())), {emptydir = true})
remove_files(path.join(bindir, path.filename(target:symbolfile())), {emptydir = true})
_uninstall_shared_libraries(target, opt)
end
-- uninstall shared library
function _uninstall_shared(target, opt)
local bindir = target:is_plat("windows", "mingw") and target:bindir() or target:libdir()
if target:is_plat("windows", "mingw") then
-- uninstall *.lib for shared/windows (*.dll) target
-- @see https://github.com/xmake-io/xmake/issues/714
local libdir = target:libdir()
local targetfile = target:targetfile()
remove_files(path.join(bindir, path.filename(targetfile)), {emptydir = true})
remove_files(path.join(libdir, path.basename(targetfile) .. (target:is_plat("mingw") and ".dll.a" or ".lib")), {emptydir = true})
else
local targetfile = path.join(bindir, path.filename(target:targetfile()))
_remove_file_with_symbols(targetfile)
end
remove_files(path.join(bindir, path.filename(target:symbolfile())), {emptydir = true})
_uninstall_headers(target, opt)
_uninstall_shared_libraries(target, opt)
end
-- uninstall static library
function _uninstall_static(target, opt)
local libdir = target:libdir()
remove_files(path.join(libdir, path.filename(target:targetfile())), {emptydir = true})
remove_files(path.join(libdir, path.filename(target:symbolfile())), {emptydir = true})
_uninstall_headers(target, opt)
end
-- uninstall headeronly library
function _uninstall_headeronly(target, opt)
_uninstall_headers(target, opt)
end
-- uninstall moduleonly library
function _uninstall_moduleonly(target, opt)
_uninstall_headers(target, opt)
end
function main(target, opt)
local installdir = target:installdir()
if not installdir then
wprint("please use `xmake install -o installdir` or `set_installdir` to set install directory.")
return
end
print("uninstalling %s to %s ..", target:name(), installdir)
if target:is_binary() then
_uninstall_binary(target, opt)
elseif target:is_shared() then
_uninstall_shared(target, opt)
elseif target:is_static() then
_uninstall_static(target, opt)
elseif target:is_headeronly() then
_uninstall_headeronly(target, opt)
elseif target:is_moduleonly() then
_uninstall_moduleonly(target, opt)
end
_uninstall_files(target)
end
|
0 | repos/xmake/xmake/modules/target/action | repos/xmake/xmake/modules/target/action/install/pkgconfig_importfiles.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file pkgconfig_importfiles.lua
--
-- install pkgconfig/.pc import files
function main(target, opt)
-- check
opt = opt or {}
assert(target:is_library(), 'pkgconfig_importfiles: only support for library target(%s)!', target:name())
local installdir = target:installdir()
if not installdir then
return
end
-- get pkgconfig/.pc file
local pcfile = path.join(installdir, opt and opt.libdir or "lib", "pkgconfig", opt.filename or (target:basename() .. ".pc"))
-- get includedirs
local includedirs = opt.includedirs
-- get links and linkdirs
local links = opt.links or target:basename()
local linkdirs = opt.linkdirs
-- get libs
local libs = ""
for _, linkdir in ipairs(linkdirs) do
if linkdir ~= path.join(installdir, "lib") then
libs = libs .. " -L" .. (linkdir:gsub("\\", "/"))
end
end
libs = libs .. " -L${libdir}"
if not target:is_headeronly() then
for _, link in ipairs(links) do
libs = libs .. " -l" .. link
end
end
libs = libs:trim()
-- get cflags
local cflags = ""
for _, includedir in ipairs(includedirs) do
if includedir ~= path.join(installdir, "include") then
cflags = cflags .. " -I" .. (includedir:gsub("\\", "/"))
end
end
cflags = cflags .. " -I${includedir}"
cflags = cflags:trim()
-- trace
vprint("generating %s ..", pcfile)
-- generate a *.pc file
local file = io.open(pcfile, 'w')
if file then
file:print("prefix=%s", installdir:gsub("\\", "/"))
file:print("exec_prefix=${prefix}")
file:print("libdir=${exec_prefix}/lib")
file:print("includedir=${prefix}/include")
file:print("")
file:print("Name: %s", target:name())
file:print("Description: %s", target:name())
local version = target:get("version")
if version then
file:print("Version: %s", version)
end
file:print("Libs: %s", libs)
file:print("Cflags: %s", cflags)
file:close()
end
end
|
0 | repos/xmake/xmake/modules/target/action | repos/xmake/xmake/modules/target/action/install/main.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file main.lua
--
-- imports
import("core.base.option")
import("core.base.hashset")
import("utils.binary.deplibs", {alias = "get_depend_libraries"})
import("utils.binary.rpath", {alias = "rpath_utils"})
-- we need to get all deplibs, e.g. app -> libfoo.so -> libbar.so ...
-- @see https://github.com/xmake-io/xmake/issues/5325#issuecomment-2242597732
function _get_target_package_deplibs(target, depends, libfiles, binaryfile)
local deplibs = get_depend_libraries(binaryfile, {plat = target:plat(), arch = target:arch()})
local depends_new = hashset.new()
for _, deplib in ipairs(deplibs) do
local libname = path.filename(deplib)
if not depends:has(libname) then
depends:insert(libname)
depends_new:insert(libname)
end
end
for _, libfile in ipairs(libfiles) do
local libname = path.filename(libfile)
if depends_new:has(libname) then
_get_target_package_deplibs(target, depends, libfiles, libfile)
end
end
end
function _get_target_package_libfiles(target, opt)
if option.get("nopkgs") then
return {}
end
local libfiles = {}
for _, pkg in ipairs(target:orderpkgs(opt)) do
if pkg:enabled() and pkg:get("libfiles") then
for _, libfile in ipairs(table.wrap(pkg:get("libfiles"))) do
local filename = path.filename(libfile)
if filename:endswith(".dll") or filename:endswith(".so") or filename:find("%.so%.%d+$") or filename:endswith(".dylib") then
table.insert(libfiles, libfile)
end
end
end
end
-- we can only reserve used libraries
if target:is_binary() or target:is_shared() then
local depends = hashset.new()
_get_target_package_deplibs(target, depends, libfiles, target:targetfile())
table.remove_if(libfiles, function (_, libfile) return not depends:has(path.filename(libfile)) end)
end
return libfiles
end
-- copy file with symlinks
function _copy_file_with_symlinks(srcfile, outputdir)
if os.islink(srcfile) then
local srcfile_symlink = os.readlink(srcfile)
if not path.is_absolute(srcfile_symlink) then
srcfile_symlink = path.join(path.directory(srcfile), srcfile_symlink)
end
_copy_file_with_symlinks(srcfile_symlink, outputdir)
os.vcp(srcfile, path.join(outputdir, path.filename(srcfile)), {symlink = true, force = true})
else
os.vcp(srcfile, path.join(outputdir, path.filename(srcfile)))
end
end
-- install files
function _install_files(target)
local srcfiles, dstfiles = target:installfiles()
if srcfiles and dstfiles then
for idx, srcfile in ipairs(srcfiles) do
os.vcp(srcfile, dstfiles[idx])
end
end
for _, dep in ipairs(target:orderdeps()) do
local srcfiles, dstfiles = dep:installfiles(dep:installdir(), {interface = true})
if srcfiles and dstfiles then
for idx, srcfile in ipairs(srcfiles) do
os.vcp(srcfile, dstfiles[idx])
end
end
end
end
-- install headers
function _install_headers(target, opt)
local srcheaders, dstheaders = target:headerfiles(target:includedir(), {installonly = true})
if srcheaders and dstheaders then
for idx, srcheader in ipairs(srcheaders) do
os.vcp(srcheader, dstheaders[idx])
end
end
for _, dep in ipairs(target:orderdeps()) do
local srcfiles, dstfiles = dep:headerfiles(dep:includedir(), {installonly = true, interface = true})
if srcfiles and dstfiles then
for idx, srcfile in ipairs(srcfiles) do
os.vcp(srcfile, dstfiles[idx])
end
end
end
end
-- install shared libraries
function _install_shared_libraries(target, opt)
local bindir = target:is_plat("windows", "mingw") and target:bindir() or target:libdir()
-- get all dependent shared libraries
local libfiles = {}
for _, dep in ipairs(target:orderdeps()) do
if dep:kind() == "shared" then
local depfile = dep:targetfile()
if os.isfile(depfile) then
table.insert(libfiles, depfile)
end
end
table.join2(libfiles, _get_target_package_libfiles(dep, {interface = true}))
end
table.join2(libfiles, _get_target_package_libfiles(target))
-- deduplicate libfiles, prevent packages using the same libfiles from overwriting each other
libfiles = table.unique(libfiles)
-- do install
for _, libfile in ipairs(libfiles) do
local filename = path.filename(libfile)
local filepath = path.join(bindir, filename)
if os.isfile(filepath) and hash.sha256(filepath) ~= hash.sha256(libfile) then
wprint("'%s' already exists in install dir, we are copying '%s' to overwrite it.", filepath, libfile)
end
_copy_file_with_symlinks(libfile, bindir)
end
end
-- update install rpath, we can only get and update rpathdirs with `{installonly = true}`
-- e.g. add_rpathdirs("@loader_path/../lib", {installonly = true})
function _update_install_rpath(target, opt)
if target:is_plat("windows", "mingw") then
return
end
local bindir = target:bindir()
local targetfile = path.join(bindir, target:filename())
if target:policy("install.rpath") then
local result, sources = target:get_from("rpathdirs", "*")
if result and sources then
for idx, rpathdirs in ipairs(result) do
local source = sources[idx]
local extraconf = target:extraconf_from("rpathdirs", source)
for _, rpathdir in ipairs(rpathdirs) do
local extra = extraconf and extraconf[rpathdir] or nil
if extra and extra.installonly then
rpath_utils.insert(targetfile, rpathdir, {plat = target:plat(), arch = target:arch()})
else
rpath_utils.remove(targetfile, rpathdir, {plat = target:plat(), arch = target:arch()})
end
end
end
end
end
end
-- install binary
function _install_binary(target, opt)
local bindir = target:bindir()
os.mkdir(bindir)
os.vcp(target:targetfile(), bindir)
os.trycp(target:symbolfile(), path.join(bindir, path.filename(target:symbolfile())))
_install_shared_libraries(target, opt)
_update_install_rpath(target, opt)
end
-- install shared library
function _install_shared(target, opt)
local bindir = target:is_plat("windows", "mingw") and target:bindir() or target:libdir()
os.mkdir(bindir)
local targetfile = target:targetfile()
if target:is_plat("windows", "mingw") then
-- install *.lib for shared/windows (*.dll) target
-- @see https://github.com/xmake-io/xmake/issues/714
os.vcp(target:targetfile(), bindir)
local libdir = target:libdir()
local targetfile_lib = path.join(path.directory(targetfile), path.basename(targetfile) .. (target:is_plat("mingw") and ".dll.a" or ".lib"))
if os.isfile(targetfile_lib) then
os.mkdir(libdir)
os.vcp(targetfile_lib, libdir)
end
else
-- install target with soname and symlink
_copy_file_with_symlinks(targetfile, bindir)
end
os.trycp(target:symbolfile(), path.join(bindir, path.filename(target:symbolfile())))
_install_headers(target, opt)
_install_shared_libraries(target, opt)
end
-- install static library
function _install_static(target, opt)
local libdir = target:libdir()
os.mkdir(libdir)
os.vcp(target:targetfile(), libdir)
os.trycp(target:symbolfile(), path.join(libdir, path.filename(target:symbolfile())))
_install_headers(target, opt)
end
-- install headeronly library
function _install_headeronly(target, opt)
_install_headers(target, opt)
end
-- install moduleonly library
function _install_moduleonly(target, opt)
_install_headers(target, opt)
end
function main(target, opt)
local installdir = target:installdir()
if not installdir then
wprint("please use `xmake install -o installdir` or `set_installdir` to set install directory.")
return
end
print("installing %s to %s ..", target:name(), installdir)
if target:is_binary() then
_install_binary(target, opt)
elseif target:is_shared() then
_install_shared(target, opt)
elseif target:is_static() then
_install_static(target, opt)
elseif target:is_headeronly() then
_install_headeronly(target, opt)
elseif target:is_moduleonly() then
_install_moduleonly(target, opt)
end
_install_files(target)
end
|
0 | repos/xmake/xmake/modules/target/action | repos/xmake/xmake/modules/target/action/install/cmake_importfiles.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file cmake_importfiles.lua
--
-- imports
import("core.project.project")
-- get the lib file of the target
function _get_libfile(target, installdir)
local libfile = path.filename(target:targetfile())
if target:is_plat("windows") then
libfile = libfile:gsub("%.dll$", ".lib")
elseif target:is_plat("mingw") then
if os.isfile(path.join(installdir, "lib", libfile:gsub("%.dll$", ".dll.a"))) then
libfile = libfile:gsub("%.dll$", ".dll.a")
else
libfile = libfile:gsub("%.dll$", ".lib")
end
end
return libfile
end
-- get the builtin variables
function _get_builtinvars(target, installdir)
return {TARGETNAME = target:name(),
PROJECTNAME = project.name() or target:name(),
TARGETFILENAME = target:targetfile() and _get_libfile(target, installdir),
TARGETKIND = target:is_headeronly() and "INTERFACE" or (target:is_shared() and "SHARED" or "STATIC"),
PACKAGE_VERSION = target:get("version") or "1.0.0",
TARGET_PTRBYTES = target:is_arch("x86", "i386") and "4" or "8"}
end
-- install cmake config file
function _install_cmake_configfile(target, installdir, filename, opt)
-- get import file path
local projectname = project.name() or target:name()
local importfile_src = path.join(os.programdir(), "scripts", "cmake_importfiles", filename)
local importfile_dst = path.join(installdir, opt and opt.libdir or "lib", "cmake", projectname, (filename:gsub("xxx", projectname)))
-- trace
vprint("generating %s ..", importfile_dst)
-- get the builtin variables
local builtinvars = _get_builtinvars(target, installdir)
-- copy and replace builtin variables
local content = io.readfile(importfile_src)
if content then
content = content:split("#######################+#")[1]
content = content:gsub("(@(.-)@)", function(_, variable)
variable = variable:trim()
local value = builtinvars[variable]
return type(value) == "function" and value() or value
end)
io.writefile(importfile_dst, content)
end
end
-- append target to cmake config file
function _append_cmake_configfile(target, installdir, filename, opt)
-- get import file path
local projectname = project.name() or target:name()
local importfile_src = path.join(os.programdir(), "scripts", "cmake_importfiles", filename)
local importfile_dst = path.join(installdir, opt and opt.libdir or "lib", "cmake", projectname, (filename:gsub("xxx", projectname)))
-- get the builtin variables
local builtinvars = _get_builtinvars(target, installdir)
-- generate the file if not exist / file is outdated
if target:is_headeronly() or not os.isfile(importfile_dst) or os.mtime(importfile_dst) < os.mtime(target:targetfile()) then
_install_cmake_configfile(target, installdir, filename, opt)
end
-- copy and replace builtin variables
local content = io.readfile(importfile_src)
local dst_content = io.readfile(importfile_dst)
if content then
content = content:split("#######################+#")[2]
content = content:gsub("(@(.-)@)", function(_, variable)
variable = variable:trim()
local value = builtinvars[variable]
return type(value) == "function" and value() or value
end)
content = content:trim()
-- check if the target already exists
if not dst_content:match(format("%sTargets.cmake", target:name())) then
io.writefile(importfile_dst, dst_content:trim() .. "\n\n" .. content .. "\n")
end
end
end
-- install cmake target file
function _install_cmake_targetfile(target, installdir, filename, opt)
-- get import file path
local projectname = project.name() or target:name()
local importfile_src = path.join(os.programdir(), "scripts", "cmake_importfiles", filename)
local importfile_dst = path.join(installdir, opt and opt.libdir or "lib", "cmake", projectname, (filename:gsub("xxx", target:name())))
-- trace
vprint("generating %s ..", importfile_dst)
-- get the builtin variables
local builtinvars = _get_builtinvars(target, installdir)
-- copy and replace builtin variables
local content = io.readfile(importfile_src)
if content then
content = content:gsub("(@(.-)@)", function(_, variable)
variable = variable:trim()
local value = builtinvars[variable]
return type(value) == "function" and value() or value
end)
io.writefile(importfile_dst, content)
end
end
-- install .cmake import files
function main(target, opt)
-- check
opt = opt or {}
assert(target:is_library(), 'cmake_importfiles: only support for library target(%s)!', target:name())
-- get install directory
local installdir = target:installdir()
if not installdir then
return
end
-- do install
_append_cmake_configfile(target, installdir, "xxxConfig.cmake", opt)
_install_cmake_configfile(target, installdir, "xxxConfigVersion.cmake", opt)
_install_cmake_targetfile(target, installdir, "xxxTargets.cmake", opt)
if not target:is_headeronly() then
if is_mode("debug") then
_install_cmake_targetfile(target, installdir, "xxxTargets-debug.cmake", opt)
else
_install_cmake_targetfile(target, installdir, "xxxTargets-release.cmake", opt)
end
end
end
|
0 | repos/xmake/xmake/modules/target/action | repos/xmake/xmake/modules/target/action/clean/main.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file main.lua
--
-- imports
import("core.base.option")
import("private.action.clean.remove_files")
import("private.cache.build_cache")
-- the builtin clean main entry
function main(target)
-- is phony?
if target:is_phony() then
return
end
-- remove the target file
local targetfile = target:targetfile()
remove_files(targetfile)
-- remove import library of the target file
-- @see https://github.com/xmake-io/xmake/issues/3052
if target:is_plat("windows") and target:is_shared() then
local expfile = path.join(path.directory(targetfile), path.basename(targetfile) .. ".exp")
local libfile = path.join(path.directory(targetfile), path.basename(targetfile) .. ".lib")
if os.isfile(expfile) then
remove_files(libfile)
remove_files(expfile)
end
end
-- remove the symbol file
remove_files(target:symbolfile())
-- remove the c/c++ precompiled header file
remove_files(target:pcoutputfile("c"))
remove_files(target:pcoutputfile("cxx"))
-- remove the clean files
remove_files(target:get("cleanfiles"))
-- remove all?
if option.get("all") then
-- remove config files
local _, configfiles = target:configfiles()
remove_files(configfiles)
-- remove all dependent files for each platform
remove_files(target:dependir({root = true}))
-- remove all object files for each platform
remove_files(target:objectdir({root = true}))
-- remove all autogen files for each platform
remove_files(target:autogendir({root = true}))
-- clean build cache
build_cache.clean()
else
-- remove dependent files for the current platform
remove_files(target:dependir())
-- remove object files for the current platform
remove_files(target:objectdir())
-- remove autogen files for the current platform
remove_files(target:autogendir())
end
end
|
0 | repos/xmake/xmake/modules/private | repos/xmake/xmake/modules/private/cache/build_cache.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file build_cache.lua
--
-- imports
import("core.base.bytes")
import("core.base.hashset")
import("core.base.global")
import("core.cache.memcache")
import("core.project.config")
import("core.project.policy")
import("core.project.project")
import("utils.ci.is_running", {alias = "ci_is_running"})
import("private.service.client_config")
import("private.service.remote_cache.client", {alias = "remote_cache_client"})
-- get memcache
function _memcache()
local cache = _g.memcache
if not cache then
cache = memcache.cache("build_cache")
_g.memcache = cache
end
return cache
end
-- get exist info
function _get_existinfo()
local existinfo = _g.existinfo
if existinfo == nil then
existinfo = remote_cache_client.singleton():existinfo()
_g.existinfo = existinfo
end
return existinfo
end
-- is enabled?
function is_enabled(target)
local key = tostring(target or "all")
local result = _memcache():get2("enabled", key)
if result == nil then
-- target may be option instance
if result == nil and target and target.policy then
result = target:policy("build.ccache")
end
if result == nil and os.isfile(os.projectfile()) then
local policy = project.policy("build.ccache")
if policy ~= nil then
result = policy
end
end
-- disable ccache on ci
if result == nil and ci_is_running() then
result = false
end
-- disable ccache for msvc, because cl.exe preprocessor is too slower
-- @see https://github.com/xmake-io/xmake/issues/3532
if result == nil and is_host("windows") and
target and target.has_tool and target:has_tool("cxx", "cl") then
result = false
end
if result == nil then
result = config.get("ccache")
end
result = result or false
_memcache():set2("enabled", key)
end
return result
end
-- is supported?
function is_supported(sourcekind)
local sourcekinds = _g.sourcekinds
if sourcekinds == nil then
sourcekinds = hashset.of("cc", "cxx", "mm", "mxx")
_g.sourcekinds = sourcekinds
end
return sourcekinds:has(sourcekind)
end
-- get cache key
function cachekey(program, cppinfo, envs)
local cppfile = cppinfo.cppfile
local cppflags = cppinfo.cppflags
local items = {program}
for _, cppflag in ipairs(cppflags) do
if cppflag:startswith("-D") or cppflag:startswith("/D") then
-- ignore `-Dxx` to improve the cache hit rate, as some source files may not use the defined macros.
-- @see https://github.com/xmake-io/xmake/issues/2425
else
table.insert(items, cppflag)
end
end
table.sort(items)
table.insert(items, hash.xxhash128(cppfile))
if envs then
local basename = path.basename(program)
if basename == "cl" then
for _, name in ipairs({"WindowsSDKVersion", "VCToolsVersion", "LIB"}) do
local val = envs[name]
if val then
table.insert(items, val)
end
end
end
end
return hash.xxhash128(bytes(table.concat(items, "")))
end
-- get cache root directory
function rootdir()
local cachedir = _g.cachedir
if not cachedir then
cachedir = config.get("ccachedir")
if not cachedir and project.policy("build.ccache.global_storage") then
cachedir = path.join(global.directory(), ".build_cache")
end
if not cachedir then
cachedir = path.join(config.buildir(), ".build_cache")
end
_g.cachedir = path.absolute(cachedir)
end
return cachedir
end
-- clean cached files
function clean()
os.rm(rootdir())
if remote_cache_client.is_connected() then
client_config.load()
remote_cache_client.singleton():clean()
end
end
-- get hit rate
function hitrate()
local cache_hit_count = (_g.cache_hit_count or 0)
local total_count = (_g.total_count or 0)
if total_count > 0 then
return math.floor(cache_hit_count * 100 / total_count)
end
return 0
end
-- dump stats
function dump_stats()
local total_count = (_g.total_count or 0)
local cache_hit_count = (_g.cache_hit_count or 0)
local cache_miss_count = total_count - cache_hit_count
local newfiles_count = (_g.newfiles_count or 0)
local remote_hit_count = (_g.remote_hit_count or 0)
local remote_newfiles_count = (_g.remote_newfiles_count or 0)
local preprocess_error_count = (_g.preprocess_error_count or 0)
local compile_fallback_count = (_g.compile_fallback_count or 0)
local compile_total_time = (_g.compile_total_time or 0)
local cache_hit_total_time = (_g.cache_hit_total_time or 0)
local cache_miss_total_time = (_g.cache_miss_total_time or 0)
vprint("")
vprint("build cache stats:")
vprint("cache directory: %s", rootdir())
vprint("cache hit rate: %d%%", hitrate())
vprint("cache hit: %d", cache_hit_count)
vprint("cache hit total time: %0.3fs", cache_hit_total_time / 1000.0)
vprint("cache miss: %d", cache_miss_count)
vprint("cache miss total time: %0.3fs", cache_miss_total_time / 1000.0)
vprint("new cached files: %d", newfiles_count)
vprint("remote cache hit: %d", remote_hit_count)
vprint("remote new cached files: %d", remote_newfiles_count)
vprint("preprocess failed: %d", preprocess_error_count)
vprint("compile fallback count: %d", compile_fallback_count)
vprint("compile total time: %0.3fs", compile_total_time / 1000.0)
vprint("")
end
-- get object file
function get(cachekey)
_g.total_count = (_g.total_count or 0) + 1
local objectfile_cached = path.join(rootdir(), cachekey:sub(1, 2):lower(), cachekey)
local objectfile_infofile = objectfile_cached .. ".txt"
if os.isfile(objectfile_cached) then
_g.cache_hit_count = (_g.cache_hit_count or 0) + 1
return objectfile_cached, objectfile_infofile
elseif remote_cache_client.is_connected() then
return try
{
function ()
if not remote_cache_client.singleton():unreachable() then
local exists, extrainfo = remote_cache_client.singleton():pull(cachekey, objectfile_cached)
if exists and os.isfile(objectfile_cached) then
_g.cache_hit_count = (_g.cache_hit_count or 0) + 1
_g.remote_hit_count = (_g.remote_hit_count or 0) + 1
if extrainfo then
io.save(objectfile_infofile, extrainfo)
end
return objectfile_cached, objectfile_infofile
end
end
end,
catch
{
function (errors)
if errors and policy.build_warnings() then
cprint("${color.warning}fallback to the local cache, %s", tostring(errors))
end
end
}
}
end
end
-- put object file
function put(cachekey, objectfile, extrainfo)
local objectfile_cached = path.join(rootdir(), cachekey:sub(1, 2):lower(), cachekey)
local objectfile_infofile = objectfile_cached .. ".txt"
os.cp(objectfile, objectfile_cached)
if extrainfo then
io.save(objectfile_infofile, extrainfo)
end
_g.newfiles_count = (_g.newfiles_count or 0) + 1
if remote_cache_client.is_connected() then
try
{
function ()
if not remote_cache_client.singleton():unreachable() then
-- this file does not exist in remote server? push it to server
--
-- we use the bloom filter to approximate whether it exists or not,
-- which may result in a few less files being uploaded, but that's fine.
local existinfo = _get_existinfo()
if not existinfo or not existinfo:get(cachekey) then
-- existinfo is just an initial snapshot, we need to go further and determine if the current file exists
local cacheinfo = remote_cache_client.singleton():cacheinfo(cachekey)
if not cacheinfo or not cacheinfo.exists then
_g.remote_newfiles_count = (_g.remote_newfiles_count or 0) + 1
remote_cache_client.singleton():push(cachekey, objectfile, extrainfo)
end
end
end
end,
catch
{
function (errors)
if errors and policy.build_warnings() then
cprint("${color.warning}fallback to the local cache, %s", tostring(errors))
end
end
}
}
end
end
-- build with cache
function build(program, argv, opt)
-- do preprocess
opt = opt or {}
local preprocess = assert(opt.preprocess, "preprocessor not found!")
local compile = assert(opt.compile, "compiler not found!")
local cppinfo = preprocess(program, argv, opt)
if cppinfo then
local cachekey = cachekey(program, cppinfo, opt.envs)
local cache_hit_start_time = os.mclock()
local objectfile_cached, objectfile_infofile = get(cachekey)
if objectfile_cached then
os.cp(objectfile_cached, cppinfo.objectfile)
-- we need to update mtime for incremental compilation
-- @see https://github.com/xmake-io/xmake/issues/2620
os.touch(cppinfo.objectfile, {mtime = os.time()})
-- we need to get outdata/errdata to show warnings,
-- @see https://github.com/xmake-io/xmake/issues/2452
if objectfile_infofile and os.isfile(objectfile_infofile) then
local extrainfo = io.load(objectfile_infofile)
cppinfo.outdata = extrainfo.outdata
cppinfo.errdata = extrainfo.errdata
end
_g.cache_hit_total_time = (_g.cache_hit_total_time or 0) + (os.mclock() - cache_hit_start_time)
else
-- do compile
local preprocess_outdata = cppinfo.outdata
local preprocess_errdata = cppinfo.errdata
local compile_start_time = os.mclock()
local compile_fallback = opt.compile_fallback
if compile_fallback then
local ok = try {function () compile(program, cppinfo, opt); return true end}
if not ok then
-- we fallback to compile original source file if compiling preprocessed file fails.
-- https://github.com/xmake-io/xmake/issues/2467
local outdata, errdata = compile_fallback()
cppinfo.outdata = outdata
cppinfo.errdata = errdata
_g.compile_fallback_count = (_g.compile_fallback_count or 0) + 1
end
else
compile(program, cppinfo, opt)
end
-- if no compiler output, we need use preprocessor output, because it maybe contains warning output
if not cppinfo.outdata or #cppinfo.outdata == 0 then
cppinfo.outdata = preprocess_outdata
end
if not cppinfo.errdata or #cppinfo.errdata == 0 then
cppinfo.errdata = preprocess_errdata
end
_g.compile_total_time = (_g.compile_total_time or 0) + (os.mclock() - compile_start_time)
if cachekey then
local extrainfo
if cppinfo.outdata and #cppinfo.outdata ~= 0 then
extrainfo = extrainfo or {}
extrainfo.outdata = cppinfo.outdata
end
if cppinfo.errdata and #cppinfo.errdata ~= 0 then
extrainfo = extrainfo or {}
extrainfo.errdata = cppinfo.errdata
end
local cache_miss_start_time = os.mclock()
put(cachekey, cppinfo.objectfile, extrainfo)
_g.cache_miss_total_time = (_g.cache_miss_total_time or 0) + (os.mclock() - cache_miss_start_time)
end
end
os.rm(cppinfo.cppfile)
else
_g.preprocess_error_count = (_g.preprocess_error_count or 0) + 1
end
return cppinfo
end
|
0 | repos/xmake/xmake/modules/private | repos/xmake/xmake/modules/private/async/buildjobs.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file buildjobs.lua
--
-- imports
import("core.base.hashset")
-- build jobs for node dependencies
function _build_jobs_for_nodedeps(nodes, jobs, rootjob, jobrefs, nodeinfo)
local targetjob_ref = jobrefs[nodeinfo.name]
if targetjob_ref then
jobs:add(targetjob_ref, rootjob)
else
local nodejob = jobs:add(nodeinfo.job, rootjob)
if nodejob then
jobrefs[nodeinfo.name] = nodejob
for _, depname in ipairs(nodeinfo.deps) do
local dep = nodes[depname]
if dep then
_build_jobs_for_nodedeps(nodes, jobs, nodejob, jobrefs, dep)
end
end
end
end
end
-- build jobs
--
-- @param nodes the node graph dependencies
-- @param jobs the jobpool object
-- @param rootjob the root job
--
-- @code
--[[
nodes["node1"] = {
name = "node1",
deps = {"node2", "node3"},
job = batchjobs:newjob("/job/node1", function(index, total, opt)
end)
}
--]]
function main(nodes, jobs, rootjob)
local depset = hashset.new()
for _, nodeinfo in pairs(nodes) do
assert(nodeinfo.job)
for _, depname in ipairs(nodeinfo.deps) do
depset:insert(depname)
end
end
local nodes_root = {}
for _, nodeinfo in pairs(nodes) do
if not depset:has(nodeinfo.name) then
table.insert(nodes_root, nodeinfo)
end
end
local jobrefs = {}
for _, nodeinfo in pairs(nodes_root) do
_build_jobs_for_nodedeps(nodes, jobs, rootjob, jobrefs, nodeinfo)
end
end
|
0 | repos/xmake/xmake/modules/private | repos/xmake/xmake/modules/private/async/jobpool.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file jobpool.lua
--
-- imports
import("core.base.object")
import("core.base.list")
import("core.base.hashset")
-- define module
local jobpool = jobpool or object {_init = {"_size", "_rootjob", "_leafjobs"}}
-- the job status
local JOB_STATUS_FREE = 1
local JOB_STATUS_PENDING = 2
local JOB_STATUS_FINISHED = 3
-- get jobs size
function jobpool:size()
return self._size
end
-- get root job
function jobpool:rootjob()
return self._rootjob
end
-- new run job
--
-- e.g.
-- local job = jobpool:newjob("xxx", function (index, total) end)
-- jobpool:add(job, rootjob1)
-- jobpool:add(job, rootjob2)
-- jobpool:add(job, rootjob3)
--
function jobpool:newjob(name, run, opt)
opt = opt or {}
return {name = name, run = run, distcc = opt.distcc, status = JOB_STATUS_FREE}
end
-- add run job to the given job node
--
-- e.g.
-- local job = jobpool:addjob("xxx", function (index, total) end, {rootjob = rootjob})
--
-- @param name the job name
-- @param run the run command/script
-- @param opt the options (rootjob, distcc)
-- we can support distcc build if distcc is true
--
function jobpool:addjob(name, run, opt)
opt = opt or {}
return self:add({name = name, run = run, distcc = opt.distcc, status = JOB_STATUS_FREE}, opt.rootjob)
end
-- add job to the given job node
--
-- @param job the job
-- @param rootjob the root job node (optional)
--
function jobpool:add(job, rootjob)
-- add job to the root job
rootjob = rootjob or self:rootjob()
rootjob._deps = rootjob._deps or hashset.new()
rootjob._deps:insert(job)
-- attach parents node
local parents = job._parents
if not parents then
parents = {}
job._parents = parents
self._size = self._size + 1 -- @note only update number for new job without parents
end
table.insert(parents, rootjob)
-- in group? attach the group node
local group = self._group
if group then
job._deps = job._deps or hashset.new()
job._deps:insert(group)
group._parents = group._parents or {}
table.insert(group._parents, job)
end
return job
end
-- get a free job from the leaf jobs
function jobpool:getfree()
if self:size() == 0 then
return
end
-- get a free job from the leaf jobs
local leafjobs = self:_getleafjobs()
if not leafjobs:empty() then
-- try to get next free job fastly
if self._nextfree then
local job = self._nextfree
local nextfree = leafjobs:prev(job)
if nextfree ~= job and self:_isfree(nextfree) then
self._nextfree = nextfree
else
self._nextfree = nil
end
job.status = JOB_STATUS_PENDING
return job
end
-- find the next free job
local removed_jobs = {}
for job in leafjobs:ritems() do
if self:_isfree(job) then
local nextfree = leafjobs:prev(job)
if nextfree ~= job and self:_isfree(nextfree) then
self._nextfree = nextfree
end
job.status = JOB_STATUS_PENDING
return job
elseif job.group or job.status == JOB_STATUS_FINISHED then
table.insert(removed_jobs, job)
end
end
-- not found? if remove group and referenced node exist,
-- we try to remove them and find the next free job again
if #removed_jobs > 0 then
for _, job in ipairs(removed_jobs) do
self:remove(job)
end
for job in leafjobs:ritems() do
if self:_isfree(job) then
local nextfree = leafjobs:prev(job)
if nextfree ~= job and self:_isfree(nextfree) then
self._nextfree = nextfree
end
job.status = JOB_STATUS_PENDING
return job
end
end
end
end
end
-- remove the given job from the leaf jobs
function jobpool:remove(job)
assert(self:size() > 0)
local leafjobs = self:_getleafjobs()
if not leafjobs:empty() then
assert(job ~= self._nextfree)
-- remove this job from leaf jobs
job.status = JOB_STATUS_FINISHED
leafjobs:remove(job)
-- get parents node
local parents = assert(job._parents, "invalid job without parents node!")
-- update all parents nodes
for _, p in ipairs(parents) do
-- we need to avoid adding it to leafjobs repeatly, it will cause dead-loop when poping group job
-- @see https://github.com/xmake-io/xmake/issues/2740
if not p._leaf then
p._deps:remove(job)
if p._deps:empty() and self._size > 0 then
p._leaf = true
leafjobs:insert_first(p)
end
end
end
end
end
-- enter group
--
-- @param name the group name
-- @param opt the options, e.g. {rootjob = ..}
--
function jobpool:group_enter(name, opt)
opt = opt or {}
assert(not self._group, "jobpool: cannot enter group(%s)!", name)
self._group = {name = name, group = true, rootjob = opt.rootjob}
end
-- leave group
--
-- @return the group node
--
function jobpool:group_leave()
local group = self._group
self._group = nil
if group then
if group._parents then
return group
else
-- we just return the rootjob if there is not any jobs in this group
return group.rootjob
end
end
end
-- is free job?
-- we need to ignore group node (empty job) and referenced node (finished job)
function jobpool:_isfree(job)
if job and job.status == JOB_STATUS_FREE and not job.group then
return true
end
end
-- get leaf jobs
function jobpool:_getleafjobs()
local leafjobs = self._leafjobs
if leafjobs == nil then
leafjobs = list.new()
local refs = {}
self:_genleafjobs(self:rootjob(), leafjobs, refs)
self._leafjobs = leafjobs
end
return leafjobs
end
-- generate all leaf jobs from the given job
function jobpool:_genleafjobs(job, leafjobs, refs)
local deps = job._deps
if deps and not deps:empty() then
for _, dep in deps:keys() do
local depkey = tostring(dep)
if not refs[depkey] then
refs[depkey] = true
self:_genleafjobs(dep, leafjobs, refs)
end
end
else
job._leaf = true
leafjobs:insert_last(job)
end
end
-- generate jobs tree for the given job
function jobpool:_gentree(job, refs)
local tree = {job.group and ("group(" .. job.name .. ")") or job.name}
local deps = job._deps
if deps and not deps:empty() then
for _, dep in deps:keys() do
local depkey = tostring(dep)
if refs[depkey] then
local depname = dep.group and ("group(" .. dep.name .. ")") or dep.name
table.insert(tree, "ref(" .. depname .. ")")
else
refs[depkey] = true
table.insert(tree, self:_gentree(dep, refs))
end
end
end
-- strip tree
local smalltree = hashset.new()
for _, item in ipairs(tree) do
item = table.unwrap(item)
if smalltree:size() < 16 or type(item) == "table" then
smalltree:insert(item)
else
smalltree:insert("...")
end
end
return smalltree:to_array()
end
-- tostring
function jobpool:__tostring()
local refs = {}
return string.serialize(self:_gentree(self:rootjob(), refs), {indent = 2, orderkeys = true})
end
-- new a jobpool
function new()
return jobpool {0, {name = "root"}, nil}
end
|
0 | repos/xmake/xmake/modules/private | repos/xmake/xmake/modules/private/async/runjobs.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file runjobs.lua
--
-- imports
import("async.runjobs")
-- asynchronous run jobs
function main(name, jobs, opt)
runjobs(name, jobs, opt)
wprint("please use import(\"async.runjobs\") instead of private.async.runjobs!")
end
|
0 | repos/xmake/xmake/modules/private | repos/xmake/xmake/modules/private/check/checker.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file checker.lua
--
-- imports
import("core.base.option")
-- get all checkers
function checkers()
local checkers = _g._CHECKERS
if not checkers then
checkers = {
-- target api checkers
["api.target.version"] = {description = "Check version configuration in target."},
["api.target.kind"] = {description = "Check kind configuration in target.", build = true},
["api.target.strip"] = {description = "Check strip configuration in target.", build = true},
["api.target.optimize"] = {description = "Check optimize configuration in target.", build = true},
["api.target.symbols"] = {description = "Check symbols configuration in target.", build = true},
["api.target.fpmodels"] = {description = "Check fpmodels configuration in target.", build = true},
["api.target.warnings"] = {description = "Check warnings configuration in target.", build = true},
["api.target.languages"] = {description = "Check languages configuration in target.", build = true},
["api.target.vectorexts"] = {description = "Check vectorexts configuration in target.", build = true},
["api.target.exceptions"] = {description = "Check exceptions configuration in target.", build = true},
["api.target.encodings"] = {description = "Check encodings configuration in target.", build = true},
["api.target.packages"] = {description = "Check packages configuration in target."},
["api.target.files"] = {description = "Check files configuration in target."},
["api.target.headerfiles"] = {description = "Check header files configuration in target."},
["api.target.installfiles"] = {description = "Check install files configuration in target."},
["api.target.configfiles"] = {description = "Check config files configuration in target."},
["api.target.linkdirs"] = {description = "Check linkdirs configuration in target.", build = true},
["api.target.includedirs"] = {description = "Check includedirs configuration in target.", build = true},
["api.target.frameworkdirs"] = {description = "Check frameworkdirs configuration in target.", build = true},
["api.target.cflags"] = {description = "Check c compiler flags configuration in target."},
["api.target.cxflags"] = {description = "Check c/c++ compiler flags configuration in target."},
["api.target.cxxflags"] = {description = "Check c++ compiler flags configuration in target."},
["api.target.asflags"] = {description = "Check assembler flags configuration in target."},
["api.target.ldflags"] = {description = "Check binary linker flags configuration in target."},
["api.target.shflags"] = {description = "Check shared library linker flags configuration in target."},
["api.target.license"] = {description = "Check license in target and packages.", build = true},
-- cuda checkers
["cuda.devlink"] = {description = "Check devlink for targets.", build_failure = true},
-- clang tidy checker
["clang.tidy"] = {description = "Check project code using clang-tidy.", showstats = false}
}
_g._CHECKERS = checkers
end
return checkers
end
-- complete checkers
function complete(complete, opt)
return try
{
function ()
local list = {}
local groupstats = {}
for name, _ in table.orderpairs(checkers()) do
local groupname = name:split(".", {plain = true})[1]
groupstats[groupname] = (groupstats[groupname] or 0) + 1
if not complete then
local limit = 16
if groupstats[groupname] < limit then
table.insert(list, name)
elseif groupstats[groupname] == limit then
table.insert(list, "...")
end
elseif name:startswith(complete) then
table.insert(list, name)
end
end
return list
end
}
end
-- update stats
function update_stats(level, count)
local stats = _g.stats
if not stats then
stats = {}
_g.stats = stats
end
count = count or 1
stats[level] = (stats[level] or 0) + count
end
-- show stats
function show_stats()
local stats = _g.stats or {}
cprint("${bright}%d${clear} notes, ${color.warning}%d${clear} warnings, ${color.error}%d${clear} errors", stats.note or 0, stats.warning or 0, stats.error or 0)
end
|
0 | repos/xmake/xmake/modules/private/check/checkers | repos/xmake/xmake/modules/private/check/checkers/cuda/devlink.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file devlink.lua
--
-- imports
import("core.base.option")
import("core.project.project")
-- https://github.com/xmake-io/xmake/issues/1976#issuecomment-1427378799
function _check_target(target, opt)
if target:is_binary() then
local sourcebatches = target:sourcebatches()
if sourcebatches and not sourcebatches["cuda.build"] then
for _, dep in ipairs(target:orderdeps()) do
if dep:is_static() then
sourcebatches = dep:sourcebatches()
if sourcebatches and sourcebatches["cuda.build"] then
local devlink = dep:policy("build.cuda.devlink") or dep:values("cuda.build.devlink")
if not devlink then
wprint('target(%s)${clear}: cuda device link is not performed! specify set_policy("build.cuda.devlink", true) to enable it', dep:name())
end
end
end
end
end
end
end
function main(opt)
if opt.target then
_check_target(opt.target, opt)
else
for _, target in pairs(project.targets()) do
_check_target(target, opt)
end
end
end
|
0 | repos/xmake/xmake/modules/private/check/checkers | repos/xmake/xmake/modules/private/check/checkers/clang/tidy.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file tidy.lua
--
-- imports
import("core.base.option")
import("core.base.task")
import("core.project.config")
import("core.project.project")
import("lib.detect.find_tool")
import("async.runjobs")
import("private.action.require.impl.packagenv")
import("private.action.require.impl.install_packages")
-- the clang.tidy options
local options = {
{"l", "list", "k", nil, "Show the clang-tidy checks list."},
{"j", "jobs", "kv", tostring(os.default_njob()),
"Set the number of parallel check jobs."},
{"q", "quiet", "k", nil, "Run clang-tidy in quiet mode."},
{nil, "fix", "k", nil, "Apply suggested fixes."},
{nil, "fix_errors", "k", nil, "Apply suggested errors fixes."},
{nil, "fix_notes", "k", nil, "Apply suggested notes fixes."},
{nil, "create", "k", nil, "Create a .clang-tidy file."},
{nil, "configfile", "kv", nil, "Specify the path of .clang-tidy or custom config file"},
{nil, "checks", "kv", nil, "Set the given checks.",
"e.g.",
" - xmake check clang.tidy --checks=\"*\""},
{"f", "files", "v", nil, "Set files path with pattern",
"e.g.",
" - xmake check clang.tidy -f src/main.c",
" - xmake check clang.tidy -f 'src/*.c" .. path.envsep() .. "src/**.cpp'"},
{nil, "target", "v", nil, "Check the sourcefiles of the given target.",
".e.g",
" - xmake check clang.tidy",
" - xmake check clang.tidy [target]"}
}
-- show checks list
function _show_list(clang_tidy)
os.execv(clang_tidy, {"--list-checks"})
end
-- create .clang-tidy config file
function _create_config(clang_tidy, opt)
local projectdir = project.directory()
local argv = {"--dump-config"}
if opt.checks then
table.insert(argv, "--checks=" .. opt.checks)
end
os.execv(clang_tidy, argv, {stdout = path.join(projectdir, ".clang-tidy"), curdir = projectdir})
end
-- add sourcefiles in target
function _add_target_files(sourcefiles, target)
table.join2(sourcefiles, (target:sourcefiles()))
end
-- check sourcefile
function _check_sourcefile(clang_tidy, sourcefile, opt)
opt = opt or {}
local projectdir = project.directory()
local argv = {}
if opt.checks then
table.insert(argv, "--checks=" .. opt.checks)
end
if opt.fix then
table.insert(argv, "--fix")
end
if opt.fix_errors then
table.insert(argv, "--fix-errors")
end
if opt.fix_notes then
table.insert(argv, "--fix-notes")
end
if opt.compdbfile then
table.insert(argv, "-p")
table.insert(argv, opt.compdbfile)
end
if opt.configfile then
table.insert(argv, "--config-file=" .. opt.configfile)
end
if opt.quiet then
table.insert(argv, "--quiet")
end
if not path.is_absolute(sourcefile) then
sourcefile = path.absolute(sourcefile, projectdir)
end
table.insert(argv, sourcefile)
os.execv(clang_tidy, argv, {curdir = projectdir})
end
-- do check
function _check(clang_tidy, opt)
opt = opt or {}
-- generate compile_commands.json first
local filename = "compile_commands.json"
local filepath = filename
if not os.isfile(filepath) then
local outputdir = os.tmpfile() .. ".dir"
filepath = outputdir and path.join(outputdir, filename) or filename
task.run("project", {quiet = true, kind = "compile_commands", lsp = "clangd", outputdir = outputdir})
end
opt.compdbfile = filepath
-- get sourcefiles
local sourcefiles = {}
if opt.files then
local files = path.splitenv(opt.files)
for _, file in ipairs(files) do
for _, filepath in ipairs(os.files(file)) do
table.insert(sourcefiles, filepath)
end
end
else
local targetname = opt.target
if targetname then
_add_target_files(sourcefiles, project.target(targetname))
else
for _, target in ipairs(project.ordertargets()) do
_add_target_files(sourcefiles, target)
end
end
end
-- check files
local jobs = tonumber(opt.jobs or "1")
runjobs("check_files", function (index)
local sourcefile = sourcefiles[index]
if sourcefile then
_check_sourcefile(clang_tidy, sourcefile, opt)
end
end, {total = #sourcefiles,
comax = jobs,
isolate = true})
end
function main(argv)
-- parse arguments
local args = option.parse(argv or {}, options, "Use clang-tidy to check project code."
, ""
, "Usage: xmake check clang.tidy [options]")
-- enter the environments of llvm
local oldenvs = packagenv.enter("llvm")
-- find clang-tidy
local packages = {}
local clang_tidy = find_tool("clang-tidy")
if not clang_tidy then
table.join2(packages, install_packages("llvm"))
end
-- enter the environments of installed packages
for _, instance in ipairs(packages) do
instance:envs_enter()
end
-- we need to force detect and flush detect cache after loading all environments
if not clang_tidy then
clang_tidy = find_tool("clang-tidy", {force = true})
end
assert(clang_tidy, "clang-tidy not found!")
-- list checks
if args.list then
_show_list(clang_tidy.program)
elseif args.create then
_create_config(clang_tidy.program, args)
else
_check(clang_tidy.program, args)
end
-- done
os.setenvs(oldenvs)
end
|
0 | repos/xmake/xmake/modules/private/check/checkers | repos/xmake/xmake/modules/private/check/checkers/api/api_checker.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file api_checker.lua
--
-- imports
import("core.base.option")
import("core.base.hashset")
import("core.project.project")
import("private.check.checker")
import("private.utils.target", {alias = "target_utils"})
-- get the most probable value
function _get_most_probable_value(value, valueset)
local result
local mindist
for v in valueset:keys() do
local dist = value:levenshtein(v)
if not mindist or dist < mindist then
mindist = dist
result = v
end
end
return result
end
function _do_show(str, opt)
_g.showed = _g.showed or {}
local showed = _g.showed
local infostr
if str then
infostr = string.format("%s: %s: %s", opt.sourcetips, opt.level_tips, str)
else
infostr = string.format("%s: %s: unknown %s value '%s'", opt.sourcetips, opt.level_tips, opt.apiname, opt.value)
end
if opt.probable_value then
infostr = string.format("%s, it may be '%s'", infostr, opt.probable_value)
end
if not showed[infostr] then
cprint(infostr)
showed[infostr] = true
return true
end
end
-- show result
function _show(apiname, value, target, opt)
opt = opt or {}
-- match level? verbose: note/warning/error, default: warning/error
local level = opt.level
if not option.get("verbose") and level == "note" then
return
end
-- get source information
local sourceinfo = target:sourceinfo(apiname, value) or {}
local sourcetips = sourceinfo.file or ""
if sourceinfo.line then
sourcetips = sourcetips .. ":" .. (sourceinfo.line or -1)
end
if #sourcetips == 0 then
sourcetips = string.format("target(%s)", target:name())
end
-- get level tips
local level_tips = "note"
if level == "warning" then
level_tips = "${color.warning}${text.warning}${clear}"
elseif level == "error" then
level_tips = "${color.error}${text.error}${clear}"
end
-- get probable value
local probable_value
if opt.valueset then
probable_value = _get_most_probable_value(value, opt.valueset)
end
if apiname:endswith("s") then
apiname = apiname:sub(1, #apiname - 1)
end
-- do show
return (opt.show or _do_show)(opt.showstr, {
apiname = apiname,
sourcetips = sourcetips,
level_tips = level_tips,
value = value,
probable_value = probable_value})
end
-- check target
function _check_target(target, apiname, valueset, level, opt)
local target_valueset = valueset
if type(opt.values) == "function" then
local target_values = opt.values(target)
if target_values then
target_valueset = hashset.from(target_values)
end
end
local values = target:get(apiname)
for _, value in ipairs(values) do
if opt.check then
local ok, errors = opt.check(target, value)
if not ok then
local reported = _show(apiname, value, target, {
show = opt.show,
showstr = errors,
level = level})
if reported then
checker.update_stats(level)
end
end
elseif not target_valueset:has(value) then
local reported = _show(apiname, value, target, {
show = opt.show,
valueset = target_valueset,
level = level})
if reported then
checker.update_stats(level)
end
end
end
end
-- check flag
-- @see https://github.com/xmake-io/xmake/issues/3594
function check_flag(target, toolinst, flagkind, flag)
local extraconf = target:extraconf(flagkind)
flag = target_utils.flag_belong_to_tool(target, flag, toolinst, extraconf)
if flag then
extraconf = extraconf and extraconf[flag]
if not extraconf or not extraconf.force then
return toolinst:has_flags(flag)
end
end
return true
end
-- check api configuration in targets
function check_targets(apiname, opt)
opt = opt or {}
local level = opt.level or "warning"
local valueset
if opt.values and type(opt.values) ~= "function" then
valueset = hashset.from(opt.values)
else
valueset = hashset.new()
end
if opt.target then
_check_target(opt.target, apiname, valueset, level, opt)
else
for _, target in pairs(project.targets()) do
_check_target(target, apiname, valueset, level, opt)
end
end
end
|
0 | repos/xmake/xmake/modules/private/check/checkers/api | repos/xmake/xmake/modules/private/check/checkers/api/target/ldflags.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file ldflags.lua
--
-- imports
import("core.tool.compiler")
import(".api_checker")
function main(opt)
opt = opt or {}
api_checker.check_targets("ldflags", table.join(opt, {check = function(target, value)
if target:is_binary() then
local linker = target:linker()
if not api_checker.check_flag(target, linker, "ldflags", value) then
return false, string.format("%s: unknown linker flag '%s'", linker:name(), value)
end
end
return true
end}))
end
|
0 | repos/xmake/xmake/modules/private/check/checkers/api | repos/xmake/xmake/modules/private/check/checkers/api/target/symbols.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file symbols.lua
--
-- imports
import(".api_checker")
function main(opt)
opt = opt or {}
api_checker.check_targets("symbols", table.join(opt, {values = function (target)
local values = {"none", "debug", "hidden", "hidden_cxx"}
if target:is_plat("windows") and (target:has_tool("cc", "cl") or target:has_tool("cxx", "cl")) then
table.insert(values, "edit")
table.insert(values, "embed")
end
return values
end}))
end
|
0 | repos/xmake/xmake/modules/private/check/checkers/api | repos/xmake/xmake/modules/private/check/checkers/api/target/kind.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file kind.lua
--
-- imports
import(".api_checker")
function main(opt)
opt = opt or {}
api_checker.check_targets("kind", table.join(opt, {values = {"object", "binary", "static", "shared", "headeronly", "moduleonly", "phony"}}))
end
|
0 | repos/xmake/xmake/modules/private/check/checkers/api | repos/xmake/xmake/modules/private/check/checkers/api/target/configfiles.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file configfiles.lua
--
-- imports
import(".api_checker")
function main(opt)
opt = opt or {}
api_checker.check_targets("configfiles", table.join(opt, {check = function(target, value)
value = value:gsub("[()]", "")
local configfiles = os.files(value)
if not configfiles or #configfiles == 0 then
return false, string.format("configfiles '%s' not found", value)
end
return true
end}))
end
|
0 | repos/xmake/xmake/modules/private/check/checkers/api | repos/xmake/xmake/modules/private/check/checkers/api/target/strip.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file strip.lua
--
-- imports
import(".api_checker")
function main(opt)
opt = opt or {}
api_checker.check_targets("strip", table.join(opt, {values = {"none", "debug", "all"}}))
end
|
0 | repos/xmake/xmake/modules/private/check/checkers/api | repos/xmake/xmake/modules/private/check/checkers/api/target/headerfiles.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file headerfiles.lua
--
-- imports
import(".api_checker")
function main(opt)
opt = opt or {}
api_checker.check_targets("headerfiles", table.join(opt, {check = function(target, value)
value = value:gsub("[()]", "")
local headerfiles = os.files(value)
if not headerfiles or #headerfiles == 0 then
return false, string.format("headerfiles '%s' not found", value)
end
return true
end}))
end
|
0 | repos/xmake/xmake/modules/private/check/checkers/api | repos/xmake/xmake/modules/private/check/checkers/api/target/installfiles.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file installfiles.lua
--
-- imports
import(".api_checker")
function main(opt)
opt = opt or {}
api_checker.check_targets("installfiles", table.join(opt, {check = function(target, value)
value = value:gsub("[()]", "")
local installfiles = os.files(value)
if not installfiles or #installfiles == 0 then
return false, string.format("installfiles '%s' not found", value)
end
return true
end}))
end
|
0 | repos/xmake/xmake/modules/private/check/checkers/api | repos/xmake/xmake/modules/private/check/checkers/api/target/optimize.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file optimize.lua
--
-- imports
import(".api_checker")
function main(opt)
opt = opt or {}
api_checker.check_targets("optimize", table.join(opt, {values = {"none", "fast", "faster", "fastest", "smallest", "aggressive"}}))
end
|
0 | repos/xmake/xmake/modules/private/check/checkers/api | repos/xmake/xmake/modules/private/check/checkers/api/target/cflags.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file cflags.lua
--
-- imports
import("core.tool.compiler")
import(".api_checker")
function main(opt)
opt = opt or {}
api_checker.check_targets("cflags", table.join(opt, {check = function(target, value)
local compinst = target:compiler("cc")
if not api_checker.check_flag(target, compinst, "cflags", value) then
return false, string.format("%s: unknown c compiler flag '%s'", compinst:name(), value)
end
return true
end}))
end
|
0 | repos/xmake/xmake/modules/private/check/checkers/api | repos/xmake/xmake/modules/private/check/checkers/api/target/shflags.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file shflags.lua
--
-- imports
import("core.tool.compiler")
import(".api_checker")
function main(opt)
opt = opt or {}
api_checker.check_targets("shflags", table.join(opt, {check = function(target, value)
if target:is_shared() then
local linker = target:linker()
if not api_checker.check_flag(target, linker, "shflags", value) then
return false, string.format("%s: unknown linker flag '%s'", linker:name(), value)
end
end
return true
end}))
end
|
0 | repos/xmake/xmake/modules/private/check/checkers/api | repos/xmake/xmake/modules/private/check/checkers/api/target/frameworkdirs.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file frameworkdirs.lua
--
-- imports
import(".api_checker")
function main(opt)
opt = opt or {}
api_checker.check_targets("frameworkdirs", table.join(opt, {check = function(target, value)
if not os.isdir(value) then
return false, string.format("frameworkdir '%s' not found", value)
end
return true
end}))
end
|
0 | repos/xmake/xmake/modules/private/check/checkers/api | repos/xmake/xmake/modules/private/check/checkers/api/target/encodings.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file encodings.lua
--
-- imports
import(".api_checker")
function main(opt)
opt = opt or {}
api_checker.check_targets("encodings", table.join(opt, {values = {
"none", "utf-8", "source:utf-8", "target:utf-8", "source:gb2312", "target:gb2312"}}))
end
|
0 | repos/xmake/xmake/modules/private/check/checkers/api | repos/xmake/xmake/modules/private/check/checkers/api/target/cxflags.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file cxflags.lua
--
-- imports
import("core.tool.compiler")
import(".api_checker")
function main(opt)
opt = opt or {}
api_checker.check_targets("cxflags", table.join(opt, {check = function(target, value)
local compinst = target:compiler("cxx")
if not api_checker.check_flag(target, compinst, "cxflags", value) then
return false, string.format("%s: unknown c/c++ compiler flag '%s'", compinst:name(), value)
end
return true
end}))
end
|
0 | repos/xmake/xmake/modules/private/check/checkers/api | repos/xmake/xmake/modules/private/check/checkers/api/target/asflags.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file asflags.lua
--
-- imports
import("core.tool.compiler")
import(".api_checker")
function main(opt)
opt = opt or {}
api_checker.check_targets("asflags", table.join(opt, {check = function(target, value)
local compinst = target:compiler("as")
if not api_checker.check_flag(target, compinst, "asflags", value) then
return false, string.format("%s: unknown assembler flag '%s'", compinst:name(), value)
end
return true
end}))
end
|
0 | repos/xmake/xmake/modules/private/check/checkers/api | repos/xmake/xmake/modules/private/check/checkers/api/target/exceptions.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file exceptions.lua
--
-- imports
import(".api_checker")
function main(opt)
opt = opt or {}
api_checker.check_targets("exceptions", table.join(opt, {values = {"none", "cxx", "objc", "no-cxx", "no-objc"}}))
end
|
0 | repos/xmake/xmake/modules/private/check/checkers/api | repos/xmake/xmake/modules/private/check/checkers/api/target/warnings.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file warnings.lua
--
-- imports
import(".api_checker")
function main(opt)
opt = opt or {}
api_checker.check_targets("warnings", table.join(opt, {values = {
"none", "less", "more", "extra", "all", "allextra", "everything", "pedantic", "error"}}))
end
|
0 | repos/xmake/xmake/modules/private/check/checkers/api | repos/xmake/xmake/modules/private/check/checkers/api/target/fpmodels.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file fpmodels.lua
--
-- imports
import(".api_checker")
function main(opt)
opt = opt or {}
api_checker.check_targets("fpmodels", table.join(opt, {values = {"none", "precise", "fast", "strict", "except", "noexcept"}}))
end
|
0 | repos/xmake/xmake/modules/private/check/checkers/api | repos/xmake/xmake/modules/private/check/checkers/api/target/files.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file files.lua
--
-- imports
import(".api_checker")
function main(opt)
opt = opt or {}
api_checker.check_targets("files", table.join(opt, {check = function(target, value)
local files = os.files(value)
if not files or #files == 0 then
return false, string.format("files '%s' not found", value)
end
return true
end}))
end
|
0 | repos/xmake/xmake/modules/private/check/checkers/api | repos/xmake/xmake/modules/private/check/checkers/api/target/cxxflags.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file cxxflags.lua
--
-- imports
import("core.tool.compiler")
import(".api_checker")
function main(opt)
opt = opt or {}
api_checker.check_targets("cxxflags", table.join(opt, {check = function(target, value)
local compinst = target:compiler("cxx")
if not api_checker.check_flag(target, compinst, "cxxflags", value) then
return false, string.format("%s: unknown c++ compiler flag '%s'", compinst:name(), value)
end
return true
end}))
end
|
0 | repos/xmake/xmake/modules/private/check/checkers/api | repos/xmake/xmake/modules/private/check/checkers/api/target/linkdirs.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file linkdirs.lua
--
-- imports
import(".api_checker")
function main(opt)
opt = opt or {}
api_checker.check_targets("linkdirs", table.join(opt, {check = function(target, value)
if not os.isdir(value) then
return false, string.format("linkdir '%s' not found", value)
end
return true
end}))
end
|
0 | repos/xmake/xmake/modules/private/check/checkers/api | repos/xmake/xmake/modules/private/check/checkers/api/target/vectorexts.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file vectorexts.lua
--
-- imports
import(".api_checker")
function main(opt)
opt = opt or {}
api_checker.check_targets("vectorexts", table.join(opt, {values = {
"none", "all", "sse", "sse2", "sse3", "ssse3", "sse4.2", "avx", "avx2", "avx512", "fma", "neon"}}))
end
|
0 | repos/xmake/xmake/modules/private/check/checkers/api | repos/xmake/xmake/modules/private/check/checkers/api/target/includedirs.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file includedirs.lua
--
-- imports
import(".api_checker")
function main(opt)
opt = opt or {}
api_checker.check_targets("includedirs", table.join(opt, {check = function(target, value)
if not os.isdir(value) then
return false, string.format("includedir '%s' not found", value)
end
return true
end}))
end
|
0 | repos/xmake/xmake/modules/private/check/checkers/api | repos/xmake/xmake/modules/private/check/checkers/api/target/version.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file version.lua
--
-- imports
import("core.base.semver")
import(".api_checker")
function main(opt)
opt = opt or {}
api_checker.check_targets("version", table.join(opt, {check = function(target, value)
local errors
local ok = try {
function()
semver.new(value)
return true
end,
catch {
function (errs)
errors = errs
end
}
}
return ok, errors
end, level = "error"}))
end
|
0 | repos/xmake/xmake/modules/private/check/checkers/api | repos/xmake/xmake/modules/private/check/checkers/api/target/license.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file check_licenses.lua
--
-- imports
import("core.project.project")
import("core.base.license")
import("private.check.checker")
-- show info
function _show(str)
cprint("${color.warning}${text.warning}${clear}: %s", str)
end
-- check licenses
function _check_licenses_for_package(target, package, opt)
opt = opt or {}
local target_license = target:license()
local package_license = package:license()
local package_kind = package:has_shared() and "shared"
local ok, errors = license.compatible(target_license, package_license, {library_kind = package_kind})
if not ok then
errors = errors or "you can use set_license()/set_policy() to modify/disable license"
if target_license then
errors = string.format("license(%s) of target(%s) is not compatible with license(%s) of package(%s)\n%s!", target_license, target:name(), package_license, package:name(), errors)
else
errors = string.format("target(%s) maybe is not compatible with license(%s) of package(%s), \n%s!", target:name(), package_license, package:name(), errors)
end
(opt.show or _show)(errors)
checker.update_stats("warning")
end
end
-- check licenses for all dependent packages
--
-- @see https://github.com/xmake-io/xmake/issues/1016
--
function _check_licenses_for_target(target, opt)
if target:policy("check.target_package_licenses") then
for _, pkg in ipairs(target:orderpkgs()) do
if pkg:license() then
_check_licenses_for_package(target, pkg, opt)
end
end
end
end
function main(opt)
opt = opt or {}
local target = opt.target
if target then
_check_licenses_for_target(target, opt)
else
for _, target in pairs(project.targets()) do
_check_licenses_for_target(target, opt)
end
end
end
|
0 | repos/xmake/xmake/modules/private/check/checkers/api | repos/xmake/xmake/modules/private/check/checkers/api/target/languages.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file languages.lua
--
-- imports
import(".api_checker")
function main(opt)
opt = opt or {}
local values = {
"ansi", "c89", "c90", "c99", "c11", "c17", "c23", "clatest",
"cxx98", "cxx03", "cxx11", "cxx14", "cxx17", "cxx1z", "cxx20", "cxx2a", "cxx23", "cxx2b", "cxx2c", "cxx26", "cxxlatest"
}
local languages = {}
for _, value in ipairs(values) do
table.insert(languages, value)
if value:find("xx", 1, true) then
table.insert(languages, (value:gsub("xx", "++")))
end
if value:startswith("c") then
table.insert(languages, "gnu" .. value:sub(2))
end
end
api_checker.check_targets("languages", table.join(opt, {values = languages}))
end
|
0 | repos/xmake/xmake/modules/private/check/checkers/api | repos/xmake/xmake/modules/private/check/checkers/api/target/packages.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file packages.lua
--
-- imports
import("core.project.project")
import(".api_checker")
function main(opt)
opt = opt or {}
local packages = {}
local requires = project.required_packages()
if requires then
table.join2(packages, table.orderkeys(requires))
end
api_checker.check_targets("packages", table.join(opt, {values = packages, level = "note"}))
end
|
0 | repos/xmake/xmake/modules/private | repos/xmake/xmake/modules/private/service/show_logs.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file show_logs.lua
--
-- imports
import("core.base.option")
import("private.service.server_config", {alias = "config"})
function main()
local log
local logfile = config.get("logfile")
while not log do
if os.isfile(logfile) then
log = io.open(logfile, "r")
break
end
os.sleep(1000)
end
while true do
local line = log:read("l")
if line and #line > 0 then
print(line)
else
os.sleep(500)
end
end
end
|
0 | repos/xmake/xmake/modules/private | repos/xmake/xmake/modules/private/service/connect_service.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file connect_service.lua
--
-- imports
import("core.base.option")
import("core.base.scheduler")
import("private.service.client_config", {alias = "config"})
import("private.service.remote_build.client", {alias = "remote_build_client"})
import("private.service.remote_cache.client", {alias = "remote_cache_client"})
import("private.service.distcc_build.client", {alias = "distcc_build_client"})
function _connect_remote_build_server(...)
remote_build_client(...):connect()
end
function _connect_remote_cache_server(...)
remote_cache_client(...):connect()
end
function _connect_distcc_build_server(...)
distcc_build_client(...):connect()
end
function main(...)
local connectors = {}
local default = true
if option.get("remote") then
table.insert(connectors, _connect_remote_build_server)
default = false
end
if option.get("distcc") then
table.insert(connectors, _connect_distcc_build_server)
default = false
end
if option.get("ccache") then
table.insert(connectors, _connect_remote_cache_server)
default = false
end
if default then
if config.get("remote_build") then
table.insert(connectors, _connect_remote_build_server)
end
end
for _, connect_server in ipairs(connectors) do
scheduler.co_start(connect_server, ...)
end
end
|
0 | repos/xmake/xmake/modules/private | repos/xmake/xmake/modules/private/service/rm_user.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file rm_user.lua
--
-- imports
import("core.base.option")
import("core.base.base64")
import("core.base.bytes")
import("core.base.hashset")
import("private.service.service")
import("private.service.server_config", {alias = "config"})
function main(user)
assert(user, "empty user name!")
-- get user password
cprint("Please input user ${bright}%s${clear} password:", user)
io.flush()
local pass = (io.read() or ""):trim()
assert(pass ~= "", "password is empty!")
-- compute user authorization
local token = base64.encode(user .. ":" .. pass)
token = hash.md5(bytes(token))
-- save to configs
local configs = assert(config.configs(), "configs not found!")
configs.tokens = configs.tokens or {}
local tokenset = hashset.from(configs.tokens)
if tokenset:has(token) then
tokenset:remove(token)
configs.tokens = tokenset:to_array()
else
cprint("User ${bright}%s${clear} not found!", user)
return
end
config.save(configs)
cprint("Remove user ${bright}%s${clear} ok!", user)
end
|
0 | repos/xmake/xmake/modules/private | repos/xmake/xmake/modules/private/service/client_config.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file client_config.lua
--
-- imports
import("core.base.global")
import("core.base.base64")
import("core.base.bytes")
import("core.project.config")
import("private.service.server_config")
-- get a local server token
function _get_local_server_token()
local tokens = server_config.get("tokens")
if tokens then
return tokens[1]
end
end
-- generate a default config file
function _generate_configfile()
local filepath = configfile()
assert(not _g.configs and not os.isfile(filepath))
local token = _get_local_server_token()
print("generating the config file to %s ..", filepath)
local configs = {
send_timeout = -1,
recv_timeout = -1,
connect_timeout = 10000,
remote_build = {
-- without authorization: "127.0.0.1:9691"
-- with user authorization: "[email protected]:9691"
connect = "127.0.0.1:9691",
-- with token authorization
token = token
},
remote_cache = {
connect = "127.0.0.1:9692",
token = token
},
distcc_build = {
hosts = {
-- optional configs
--
-- njob: max jobs
{connect = "127.0.0.1:9693", token = token}
}
}
}
save(configs)
end
-- get config file path
function configfile()
local projectfile = os.projectfile()
if projectfile and os.isfile(projectfile) then
local localconf = path.join(config.directory(), "service", "client.conf")
if os.isfile(localconf) then
return localconf
end
end
return path.join(global.directory(), "service", "client.conf")
end
-- get all configs
function configs()
return _g.configs
end
-- get the given config, e.g. client_config.get("remote_build.connect")
function get(name)
local value = configs()
for _, key in ipairs(name:split('.', {plain = true})) do
if type(value) == "table" then
value = value[key]
else
value = nil
break
end
end
return value
end
-- load configs
function load()
if _g.configs == nil then
local filepath = configfile()
if not os.isfile(filepath) then
_generate_configfile()
end
assert(os.isfile(filepath), "%s not found!", filepath)
_g.configs = io.load(filepath)
end
end
-- save configs
function save(configs)
local filepath = configfile()
io.save(filepath, configs, {orderkeys = true})
end
|
0 | repos/xmake/xmake/modules/private | repos/xmake/xmake/modules/private/service/stop_service.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file stop_service.lua
--
-- imports
import("core.base.option")
import("private.service.remote_build.server", {alias = "remote_build_server"})
import("private.service.remote_cache.server", {alias = "remote_cache_server"})
import("private.service.distcc_build.server", {alias = "distcc_build_server"})
function _stop_remote_build_server(...)
local pidfile = remote_build_server(...):pidfile()
if pidfile and os.isfile(pidfile) then
local pid = io.readfile(pidfile)
if pid then
pid = pid:trim()
try { function ()
if is_host("windows") then
os.run("taskkill /f /t /pid %s", pid)
else
os.run("kill -9 %s", pid)
end
print("service[%s]: stopped", pid)
end}
end
os.rm(pidfile)
end
end
function _stop_remote_cache_server(...)
local pidfile = remote_cache_server(...):pidfile()
if pidfile and os.isfile(pidfile) then
local pid = io.readfile(pidfile)
if pid then
pid = pid:trim()
try { function ()
if is_host("windows") then
os.run("taskkill /f /t /pid %s", pid)
else
os.run("kill -9 %s", pid)
end
print("service[%s]: stopped", pid)
end}
end
os.rm(pidfile)
end
end
function _stop_distcc_build_server(...)
local pidfile = distcc_build_server(...):pidfile()
if pidfile and os.isfile(pidfile) then
local pid = io.readfile(pidfile)
if pid then
pid = pid:trim()
try { function ()
if is_host("windows") then
os.run("taskkill /f /t /pid %s", pid)
else
os.run("kill -9 %s", pid)
end
print("service[%s]: stopped", pid)
end}
end
os.rm(pidfile)
end
end
function main(...)
local stoppers = {_stop_remote_build_server, _stop_remote_cache_server, _stop_distcc_build_server}
for _, stop_server in ipairs(stoppers) do
stop_server(...)
end
end
|
0 | repos/xmake/xmake/modules/private | repos/xmake/xmake/modules/private/service/server.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file server.lua
--
-- imports
import("core.base.object")
import("core.base.bytes")
import("core.base.base64")
import("core.base.hashset")
import("core.base.socket")
import("core.base.scheduler")
import("private.service.server_config", {alias = "config"})
import("private.service.message")
import("private.service.stream", {alias = "socket_stream"})
-- define module
local server = server or object()
-- init server
function server:init(daemon)
self._DAEMON = daemon
-- init authorizations
local tokens = config.get("tokens")
self:tokens_set(tokens)
-- init known hosts
local known_hosts = config.get("known_hosts")
self:known_hosts_set(known_hosts)
-- init timeout
self._SEND_TIMEOUT = config.get("send_timeout") or -1
self._RECV_TIMEOUT = config.get("recv_timeout") or -1
end
-- is daemon?
function server:daemon()
return self._DAEMON
end
-- set handler
function server:handler_set(handler)
self._HANDLER = handler
end
-- set the given listen address
function server:address_set(address)
local splitinfo = address:split(':', {plain = true})
if #splitinfo == 2 then
self._ADDR = splitinfo[1]
self._PORT = splitinfo[2]
else
self._ADDR = "127.0.0.1"
self._PORT = splitinfo[1]
end
assert(self._ADDR and self._PORT, "invalid listen address!")
end
-- get the listen address
function server:addr()
return self._ADDR
end
-- get the listen port
function server:port()
return self._PORT
end
-- get send timeout
function server:send_timeout()
return self._SEND_TIMEOUT
end
-- get recv timeout
function server:recv_timeout()
return self._RECV_TIMEOUT
end
-- get tokens
function server:tokens()
return self._TOKENS
end
-- set tokens
function server:tokens_set(tokens)
self._TOKENS = tokens and hashset.from(tokens) or hashset.new()
end
-- get known hosts
function server:known_hosts()
return self._KNOWN_HOSTS
end
-- set known hosts
function server:known_hosts_set(hosts)
self._KNOWN_HOSTS = hosts and hashset.from(hosts) or hashset.new()
end
-- we need to verify user
function server:need_verfiy()
return not self:tokens():empty()
end
-- verify user
function server:verify_user(token, peeraddr)
if not token then
return false, "client has no authorization, we need to add username to connect address or token!"
end
-- check authorization
if not self:tokens():has(token) then
return false, "user and password are incorrect!"
end
-- check known_hosts
if not self:known_hosts():empty() and peeraddr then
local addrinfo = peeraddr:split(":")
if addrinfo and #addrinfo == 2 then
local addr = addrinfo[1]
if not self:known_hosts():has(addr) then
return false, "your host address is unknown in server!"
end
end
end
return true
end
-- run main loop
function server:runloop()
assert(self._HANDLER, "no handler found!")
-- ensure only one server process
local lock = io.openlock(self:lockfile())
if not lock:trylock() then
raise("%s: has been started!", self)
end
-- save the current pid for stopping service
io.writefile(self:pidfile(), os.getpid())
-- run loop
local sock = socket.bind(self:addr(), self:port())
sock:listen(100)
print("%s: listening %s:%d ..", self, self:addr(), self:port())
io.flush()
while true do
local sock_client = sock:accept()
if sock_client then
scheduler.co_start(function (sock)
self:_handle_session(sock)
sock:close()
end, sock_client)
end
end
io.flush()
sock:close()
end
-- get class
function server:class()
return server
end
-- get pid file
function server:pidfile()
return path.join(self:workdir(), "server.pid")
end
-- get lock file
function server:lockfile()
return path.join(self:workdir(), "server.lock")
end
-- get working directory
function server:workdir()
return os.tmpfile(tostring(self)) .. ".dir"
end
-- handle session
function server:_handle_session(sock)
print("%s: %s: session connected", self, sock)
local stream = socket_stream(sock, {send_timeout = self:send_timeout(), recv_timeout = self:recv_timeout()})
while true do
local msg = stream:recv_object({timeout = -1})
if msg then
local ok = try
{
function ()
self:_HANDLER(stream, message(msg))
return true
end,
catch
{
function (errors)
vprint(errors)
end
}
}
if not ok then
break
end
else
break
end
end
print("%s: %s: session end", self, sock)
end
function server:__tostring()
return "<server>"
end
function main()
local instance = server()
instance:init()
return instance
end
|
0 | repos/xmake/xmake/modules/private | repos/xmake/xmake/modules/private/service/pull_files.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file pull_files.lua
--
-- imports
import("core.base.option")
import("private.service.remote_build.client", {alias = "remote_build_client"})
function main(filepattern, outputdir)
remote_build_client():pull(filepattern, outputdir)
end
|
0 | repos/xmake/xmake/modules/private | repos/xmake/xmake/modules/private/service/stream.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file stream.lua
--
-- imports
import("core.base.bit")
import("core.base.object")
import("core.base.socket")
import("core.base.bytes")
import("core.compress.lz4")
import("private.service.message")
-- define module
local stream = stream or object()
-- max data buffer size
local STREAM_DATA_MAXN = 10 * 1024 * 1024
-- the header flags
local HEADER_FLAG_COMPRESS_LZ4 = 1
-- init stream
function stream:init(sock, opt)
opt = opt or {}
self._SOCK = sock
self._BUFF = bytes(65536)
self._RCACHE = bytes(8192)
self._RCACHE_SIZE = 0
self._WCACHE = bytes(8192)
self._WCACHE_SIZE = 0
self._SEND_TIMEOUT = opt.send_timeout and opt.send_timeout or -1
self._RECV_TIMEOUT = opt.recv_timeout and opt.recv_timeout or -1
end
-- get socket
function stream:sock()
return self._SOCK
end
-- get send timeout
function stream:send_timeout()
return self._SEND_TIMEOUT
end
-- get send timeout
function stream:recv_timeout()
return self._RECV_TIMEOUT
end
-- flush data
function stream:flush(opt)
opt = opt or {}
local cache = self._WCACHE
local cache_size = self._WCACHE_SIZE
if cache_size > 0 then
local sock = self._SOCK
local real = sock:send(cache, {block = true, last = cache_size, timeout = opt.timeout or self:send_timeout()})
if real > 0 then
self._WCACHE_SIZE = 0
return true
end
else
return true
end
end
-- send the given bytes (small data)
function stream:send(data, start, last, opt)
opt = opt or {}
start = start or 1
last = last or data:size()
local size = last + 1 - start
assert(size <= data:size())
-- write data to cache first
local cache = self._WCACHE
local cache_size = self._WCACHE_SIZE
local cache_maxn = cache:size()
local cache_left = cache_maxn - cache_size
if size <= cache_left then
cache:copy2(cache_size + 1, data, start, last)
cache_size = cache_size + size
self._WCACHE_SIZE = cache_size
return true
elseif cache_left > 0 then
cache:copy2(cache_size + 1, data, start, start + cache_left - 1)
cache_size = cache_size + cache_left
start = start + cache_left
size = last + 1 - start
end
assert(cache_size == cache_maxn)
-- send data to socket
local sock = self._SOCK
local real = sock:send(cache, {block = true, timeout = opt.timeout or self:send_timeout()})
if real > 0 then
-- copy left data to cache
assert(size <= cache_maxn)
cache:copy2(1, data, start, last)
self._WCACHE_SIZE = size
return true
end
end
-- send message
function stream:send_msg(msg, opt)
return self:send_object(msg:body(), opt)
end
-- send object
function stream:send_object(obj, opt)
local str, errors = string.serialize(obj, {strip = true, indent = false})
if errors then
raise(errors)
end
if str then
return self:send_string(str, opt)
end
end
-- send data header
function stream:send_header(size, flags, opt)
local buff = self._BUFF
buff:u32be_set(1, size)
buff:u8_set(5, flags or 0)
return self:send(buff, 1, 5, opt)
end
-- send data
function stream:send_data(data, opt)
opt = opt or {}
local flags = 0
if opt.compress then
flags = bit.bor(flags, HEADER_FLAG_COMPRESS_LZ4)
data = lz4.compress(data)
end
local size = data:size()
assert(size < STREAM_DATA_MAXN, "too large data size(%d)", size)
if self:send_header(size, flags, opt) then
local send = 0
local cache = self._WCACHE
local cache_maxn = cache:size()
while send < size do
local left = math.min(cache_maxn, size - send)
if self:send(data, send + 1, send + left, opt) then
send = send + left
else
break
end
end
if send == size then
return true
end
end
end
-- send string
function stream:send_string(str, opt)
return self:send_data(bytes(str), opt)
end
-- send empty data
function stream:send_emptydata(opt)
return self:send_header(0, opt)
end
-- send file
function stream:send_file(filepath, opt)
-- send header
opt = opt or {}
local flags = 0
local tmpfile
local originsize = os.filesize(filepath)
if opt.compress and originsize > 0 then
flags = bit.bor(flags, HEADER_FLAG_COMPRESS_LZ4)
tmpfile = os.tmpfile()
lz4.compress_file(filepath, tmpfile)
filepath = tmpfile
end
-- send header
local size = os.filesize(filepath)
if not self:send_header(size, flags) then
return
end
-- empty file?
if size == 0 then
return 0, 0
end
-- flush cache data first
if not self:flush() then
return
end
-- send file
local ok = false
local sock = self._SOCK
local file = io.open(filepath, 'rb')
if file then
local send = sock:sendfile(file, {block = true, timeout = opt.timeout or self:send_timeout()})
if send > 0 then
ok = true
end
file:close()
end
if tmpfile then
os.tryrm(tmpfile)
end
if ok then
return originsize, size
end
end
-- send files
function stream:send_files(filepaths, opt)
local size
local compressed_size
for _, filepath in ipairs(filepaths) do
local real, compressed_real = self:send_file(filepath, opt)
if real then
size = (size or 0) + real
compressed_size = (compressed_size or 0) + compressed_real
else
return
end
end
return size, compressed_size
end
-- recv the given bytes
function stream:recv(buff, size, opt)
opt = opt or {}
assert(size <= buff:size(), "too large size(%d)", size)
-- read data from cache first
local buffsize = 0
local cache = self._RCACHE
local cache_size = self._RCACHE_SIZE
local cache_maxn = cache:size()
if size <= cache_size then
buff:copy(cache, 1, size)
cache:move(size + 1, cache_size)
cache_size = cache_size - size
self._RCACHE_SIZE = cache_size
return buff:slice(1, size)
elseif cache_size > 0 then
buff:copy(cache, 1, cache_size)
buffsize = cache_size
cache_size = 0
end
assert(cache_size == 0)
-- recv data from socket
local real = 0
local data = nil
local wait = false
local sock = self._SOCK
while buffsize < size do
real, data = sock:recv(cache)
if real > 0 then
-- append data to buffer
local leftsize = size - buffsize
if real < leftsize then
buff:copy2(buffsize + 1, data)
buffsize = buffsize + real
else
buff:copy2(buffsize + 1, data, 1, leftsize)
buffsize = buffsize + leftsize
-- move left cache to head
cache_size = real - leftsize
if cache_size > 0 then
cache:move(leftsize + 1, real)
end
self._RCACHE_SIZE = cache_size
return buff:slice(1, buffsize)
end
wait = false
elseif real == 0 and not wait then
local ok = sock:wait(socket.EV_RECV, opt.timeout or self:recv_timeout())
if ok == socket.EV_RECV then
wait = true
else
assert(ok ~= 0, "%s: recv timeout!", self)
break
end
else
break
end
end
end
-- recv message
function stream:recv_msg(opt)
local body = self:recv_object(opt)
if body then
return message(body)
end
end
-- recv object
function stream:recv_object(opt)
local str = self:recv_string(opt)
if str then
local obj, errors = str:deserialize()
if errors then
raise(errors)
end
return obj
end
end
-- recv header
function stream:recv_header(opt)
local data = self:recv(self._BUFF, 5, opt)
if data then
local size = data:u32be(1)
local flags = data:u8(5)
return size, flags
end
end
-- recv data
function stream:recv_data(opt)
local size, flags = self:recv_header(opt)
if size then
local recv = 0
assert(size < STREAM_DATA_MAXN, "too large data size(%d)", size)
local buff = bytes(size)
while recv < size do
local data = self:recv(buff:slice(recv + 1), size - recv, opt)
if data then
recv = recv + data:size()
else
break
end
end
if recv == size then
if bit.band(flags, HEADER_FLAG_COMPRESS_LZ4) == HEADER_FLAG_COMPRESS_LZ4 then
buff = lz4.decompress(buff)
end
return buff
end
end
end
-- recv string
function stream:recv_string(opt)
local data = self:recv_data(opt)
if data then
return data:str()
end
end
-- recv file
function stream:recv_file(filepath, opt)
local size, flags = self:recv_header(opt)
if size then
-- empty file? we just create an empty file
if size == 0 then
local file = io.open(filepath, "wb")
file:close()
return size
end
local result
local tmpfile = os.tmpfile({ramdisk = false})
if bit.band(flags, HEADER_FLAG_COMPRESS_LZ4) == HEADER_FLAG_COMPRESS_LZ4 then
result = self:_recv_compressed_file(lz4.decompress_stream(), tmpfile, size, opt)
else
local buff = self._BUFF
local recv = 0
local file = io.open(tmpfile, "wb")
while recv < size do
local data = self:recv(buff, math.min(buff:size(), size - recv), opt)
if data then
file:write(data)
recv = recv + data:size()
end
end
file:close()
if recv == size then
result = recv
end
end
if result then
os.cp(tmpfile, filepath)
end
os.tryrm(tmpfile)
return result
end
end
-- recv files
function stream:recv_files(filepaths, opt)
local size, decompressed_size
for _, filepath in ipairs(filepaths) do
local real, decompressed_real = self:recv_file(filepath, opt)
if real then
size = (size or 0) + real
decompressed_size = (decompressed_size or 0) + decompressed_real
else
return
end
end
return size, decompressed_size
end
-- recv compressed file
function stream:_recv_compressed_file(lz4_stream, filepath, size, opt)
local buff = self._BUFF
local recv = 0
local file = io.open(filepath, "wb")
local decompressed_size = 0
while recv < size do
local data = self:recv(buff, math.min(buff:size(), size - recv), opt)
if data then
local write = 0
local writesize = data:size()
while write < writesize do
local blocksize = math.min(writesize - write, 8192)
local real = lz4_stream:write(data, {start = write + 1, last = write + blocksize})
if real > 0 then
while true do
local decompressed_real, decompressed_data = lz4_stream:read(buff, 8192)
if decompressed_real > 0 and decompressed_data then
file:write(decompressed_data)
decompressed_size = decompressed_size + decompressed_real
else
break
end
end
end
write = write + blocksize
end
recv = recv + data:size()
end
end
file:close()
if recv == size then
return recv, decompressed_size
end
end
function stream:__tostring()
return string.format("<stream: %s>", self:sock())
end
function main(sock, opt)
local instance = stream()
instance:init(sock, opt)
return instance
end
|
0 | repos/xmake/xmake/modules/private | repos/xmake/xmake/modules/private/service/disconnect_service.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file disconnect_service.lua
--
-- imports
import("core.base.option")
import("core.base.scheduler")
import("private.service.client_config", {alias = "config"})
import("private.service.remote_build.client", {alias = "remote_build_client"})
import("private.service.distcc_build.client", {alias = "distcc_build_client"})
import("private.service.remote_cache.client", {alias = "remote_cache_client"})
function _disconnect_remote_build_server(...)
remote_build_client(...):disconnect()
end
function _disconnect_remote_cache_server(...)
remote_cache_client(...):disconnect()
end
function _disconnect_distcc_build_server(...)
distcc_build_client(...):disconnect()
end
function main(...)
local disconnectors = {}
local default = true
if option.get("remote") then
table.insert(disconnectors, _disconnect_remote_build_server)
default = false
end
if option.get("distcc") then
table.insert(disconnectors, _disconnect_distcc_build_server)
default = false
end
if option.get("ccache") then
table.insert(disconnectors, _disconnect_remote_cache_server)
default = false
end
if default then
if config.get("remote_build") then
table.insert(disconnectors, _disconnect_remote_build_server)
end
end
for _, disconnect_server in ipairs(disconnectors) do
scheduler.co_start(disconnect_server, ...)
end
end
|
0 | repos/xmake/xmake/modules/private | repos/xmake/xmake/modules/private/service/gen_token.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file gen_token.lua
--
-- imports
import("core.base.option")
import("core.base.base64")
import("core.base.bytes")
import("core.base.hashset")
import("private.service.service")
import("private.service.server_config", {alias = "config"})
-- generate a token
function _generate_token()
return hash.md5(bytes(base64.encode(hash.uuid())))
end
function main()
-- generate token
local token = _generate_token()
-- save to configs
local configs = assert(config.configs(), "configs not found!")
configs.tokens = configs.tokens or {}
if not hashset.from(configs.tokens):has(token) then
table.insert(configs.tokens, token)
else
cprint("Token ${yellow bright}%s${clear} has been added!", token)
return
end
config.save(configs)
cprint("New token ${yellow bright}%s${clear} is generated!", token)
end
|
0 | repos/xmake/xmake/modules/private | repos/xmake/xmake/modules/private/service/sync_files.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file sync_files.lua
--
-- imports
import("core.base.option")
import("private.service.remote_build.client", {alias = "remote_build_client"})
function main()
remote_build_client():sync()
end
|
0 | repos/xmake/xmake/modules/private | repos/xmake/xmake/modules/private/service/reconnect_service.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file reconnect_service.lua
--
-- imports
import("private.service.connect_service")
import("private.service.disconnect_service")
function main()
disconnect_service();
connect_service();
end
|
0 | repos/xmake/xmake/modules/private | repos/xmake/xmake/modules/private/service/message.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file message.lua
--
-- imports
import("core.base.object")
-- define module
local message = message or object()
-- the common message code
message.CODE_CONNECT = 1 -- connect server
message.CODE_DISCONNECT = 2 -- disconnect server
message.CODE_CLEAN = 3 -- clean all cached files in server
message.CODE_DATA = 4 -- send data
message.CODE_RUNCMD = 5 -- run the given command in server
message.CODE_DIFF = 6 -- diff files between server and client
message.CODE_SYNC = 7 -- sync files between server and client
message.CODE_COMPILE = 8 -- compile the given file from client in server
message.CODE_PULL = 9 -- pull the given file from server
message.CODE_PUSH = 10 -- push the given file to server
message.CODE_FILEINFO = 11 -- get the given file info in server
message.CODE_EXISTINFO = 12 -- get exists info in server (use bloom filter)
message.CODE_END = 13 -- end
-- init message
function message:init(body)
self._BODY = body
end
-- get message code
function message:code()
return self:body().code
end
-- get session id
function message:session_id()
return self:body().session_id
end
-- is connect message?
function message:is_connect()
return self:code() == message.CODE_CONNECT
end
-- is disconnect message?
function message:is_disconnect()
return self:code() == message.CODE_DISCONNECT
end
-- is diff message?
function message:is_diff()
return self:code() == message.CODE_DIFF
end
-- is sync message?
function message:is_sync()
return self:code() == message.CODE_SYNC
end
-- is compile message?
function message:is_compile()
return self:code() == message.CODE_COMPILE
end
-- is clean message?
function message:is_clean()
return self:code() == message.CODE_CLEAN
end
-- is run command message?
function message:is_runcmd()
return self:code() == message.CODE_RUNCMD
end
-- is data message?
function message:is_data()
return self:code() == message.CODE_DATA
end
-- is pull message?
function message:is_pull()
return self:code() == message.CODE_PULL
end
-- is push message?
function message:is_push()
return self:code() == message.CODE_PUSH
end
-- is fileinfo message?
function message:is_fileinfo()
return self:code() == message.CODE_FILEINFO
end
-- is existinfo message?
function message:is_existinfo()
return self:code() == message.CODE_EXISTINFO
end
-- is end message?
function message:is_end()
return self:code() == message.CODE_END
end
-- get user authorization
function message:token()
return self:body().token
end
-- is success?
function message:success()
return self:body().status == true
end
-- set status, ok or failed
function message:status_set(ok)
self:body().status = ok
end
-- get message body
function message:body()
return self._BODY
end
-- get message errors
function message:errors()
return self:body().errors
end
-- set message errors
function message:errors_set(errors)
self:body().errors = errors
end
-- clone a message
function message:clone()
local body = table.copy(self:body())
return _new(body)
end
-- dump message
function message:dump()
print(self:body())
end
-- new message
function _new(body)
local instance = message()
instance:init(body)
return instance
end
-- new connect message
function new_connect(session_id, opt)
opt = opt or {}
return _new({
code = message.CODE_CONNECT,
session_id = session_id,
token = opt.token,
xmakever = xmake.version():shortstr()
})
end
-- new disconnect message
function new_disconnect(session_id, opt)
opt = opt or {}
return _new({
code = message.CODE_DISCONNECT,
session_id = session_id,
token = opt.token
})
end
-- new diff message, e.g manifest = {["src/main.c"] = {sha256 = "", mtime = ""}}
function new_diff(session_id, manifest, opt)
opt = opt or {}
return _new({
code = message.CODE_DIFF,
session_id = session_id,
token = opt.token,
manifest = manifest,
xmakesrc = opt.xmakesrc
})
end
-- new sync message, e.g. manifest = {modified = {"src/main.c"}, inserted = {}, removed = {}}
function new_sync(session_id, manifest, opt)
opt = opt or {}
return _new({
code = message.CODE_SYNC,
session_id = session_id,
token = opt.token,
manifest = manifest,
xmakesrc = opt.xmakesrc
})
end
-- new clean message
function new_clean(session_id, opt)
opt = opt or {}
return _new({
code = message.CODE_CLEAN,
session_id = session_id,
token = opt.token,
all = opt.all
})
end
-- new run command message
function new_runcmd(session_id, program, argv, opt)
opt = opt or {}
return _new({
code = message.CODE_RUNCMD,
session_id = session_id,
token = opt.token,
program = program,
argv = argv
})
end
-- new data message
function new_data(session_id, size, opt)
opt = opt or {}
return _new({
code = message.CODE_DATA,
size = size,
session_id = session_id,
token = opt.token
})
end
-- new compile command message
function new_compile(session_id, toolname, toolkind, plat, arch, toolchain, flags, sourcename, opt)
opt = opt or {}
return _new({
code = message.CODE_COMPILE,
session_id = session_id,
token = opt.token,
toolname = toolname,
toolkind = toolkind,
cachekey = opt.cachekey,
plat = plat,
arch = arch,
toolchain = toolchain,
flags = flags,
sourcename = sourcename
})
end
-- new pull message
function new_pull(session_id, filename, opt)
opt = opt or {}
return _new({
code = message.CODE_PULL,
filename = filename,
session_id = session_id,
token = opt.token
})
end
-- new push message
function new_push(session_id, filename, opt)
opt = opt or {}
return _new({
code = message.CODE_PUSH,
filename = filename,
session_id = session_id,
token = opt.token,
extrainfo = opt.extrainfo
})
end
-- new fileinfo message
function new_fileinfo(session_id, filename, opt)
opt = opt or {}
return _new({
code = message.CODE_FILEINFO,
filename = filename,
session_id = session_id,
token = opt.token
})
end
-- new existinfo message
function new_existinfo(session_id, name, opt)
opt = opt or {}
return _new({
code = message.CODE_EXISTINFO,
name = name,
session_id = session_id,
token = opt.token
})
end
-- new end message
function new_end(session_id, opt)
opt = opt or {}
return _new({
code = message.CODE_END,
session_id = session_id,
token = opt.token
})
end
function main(body)
return _new(body)
end
|
0 | repos/xmake/xmake/modules/private | repos/xmake/xmake/modules/private/service/restart_service.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file restart_service.lua
--
-- imports
import("core.base.option")
import("private.service.stop_service")
import("private.service.start_service")
function main()
stop_service();
start_service({daemon = true});
end
|
0 | repos/xmake/xmake/modules/private | repos/xmake/xmake/modules/private/service/clean_files.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file clean_files.lua
--
-- imports
import("core.base.option")
import("core.base.scheduler")
import("private.service.client_config", {alias = "config"})
import("private.service.remote_build.client", {alias = "remote_build_client"})
import("private.service.remote_cache.client", {alias = "remote_cache_client"})
import("private.service.distcc_build.client", {alias = "distcc_build_client"})
function _clean_remote_build_server(...)
remote_build_client(...):clean()
end
function _clean_remote_cache_server(...)
remote_cache_client(...):clean()
end
function _clean_distcc_build_server(...)
distcc_build_client(...):clean()
end
function main(...)
local cleaners = {}
local default = true
if option.get("remote") then
table.insert(cleaners, _clean_remote_build_server)
default = false
end
if option.get("distcc") then
table.insert(cleaners, _clean_distcc_build_server)
default = false
end
if option.get("ccache") then
table.insert(cleaners, _clean_remote_cache_server)
default = false
end
if default then
if config.get("remote_build") then
table.insert(cleaners, _clean_remote_build_server)
end
end
for _, clean_server in ipairs(cleaners) do
scheduler.co_start(clean_server, ...)
end
end
|
0 | repos/xmake/xmake/modules/private | repos/xmake/xmake/modules/private/service/client.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file client.lua
--
-- imports
import("core.base.object")
import("core.base.socket")
import("core.base.scheduler")
import("private.service.client_config", {alias = "config"})
-- define module
local client = client or object()
-- init client
function client:init()
-- init timeout
self._SEND_TIMEOUT = config.get("send_timeout") or -1
self._RECV_TIMEOUT = config.get("recv_timeout") or -1
self._CONNECT_TIMEOUT = config.get("connect_timeout") or -1
end
-- get send timeout
function client:send_timeout()
return self._SEND_TIMEOUT
end
-- get recv timeout
function client:recv_timeout()
return self._RECV_TIMEOUT
end
-- get connect timeout
function client:connect_timeout()
return self._CONNECT_TIMEOUT
end
-- parse host address
function client:address_parse(address)
local addr, port, user
local splitinfo = address:split(':', {plain = true})
if #splitinfo == 2 then
addr = splitinfo[1]
port = splitinfo[2]
else
addr = "127.0.0.1"
port = splitinfo[1]
end
if addr and addr:find("@", 1, true) then
splitinfo = addr:split('@', {plain = true})
if #splitinfo == 2 then
user = splitinfo[1]
addr = splitinfo[2]
end
end
assert(addr and port, "invalid client address!")
return addr, port, user
end
-- get class
function client:class()
return client
end
-- get working directory
function client:workdir()
return os.tmpfile(tostring(self)) .. ".dir"
end
function client:__tostring()
return "<client>"
end
function main()
local instance = client()
instance:init()
return instance
end
|
0 | repos/xmake/xmake/modules/private | repos/xmake/xmake/modules/private/service/start_service.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file start_service.lua
--
-- imports
import("core.base.option")
import("core.project.project")
import("private.service.server_config", {alias = "config"})
import("private.service.service")
function main(opt)
-- start service
opt = opt or {}
if opt.daemon then
local argv = {"lua"}
if option.get("verbose") then
table.insert(argv, "-v")
end
if option.get("diagnosis") then
table.insert(argv, "-D")
end
table.insert(argv, "private.service.service")
table.insert(argv, "--daemon")
local logfile = config.get("logfile")
if logfile then
local logdir = path.directory(logfile)
if not os.isdir(logdir) then
os.mkdir(logdir)
end
end
local tmpdir = os.tmpfile() .. ".dir"
if not os.isdir(tmpdir) then
os.mkdir(tmpdir)
end
try
{
function()
os.execv(os.programfile(), argv, {detach = true, curdir = tmpdir, stdout = logfile, stderr = logfile})
end,
catch
{
function (errors)
io.cat(logfile)
raise(errors)
end
}
}
else
service()
end
end
|
0 | repos/xmake/xmake/modules/private | repos/xmake/xmake/modules/private/service/add_user.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file add_user.lua
--
-- imports
import("core.base.option")
import("core.base.base64")
import("core.base.bytes")
import("core.base.hashset")
import("private.service.service")
import("private.service.server_config", {alias = "config"})
function main(user)
assert(user, "empty user name!")
-- get user password
cprint("Please input user ${bright}%s${clear} password:", user)
io.flush()
local pass = (io.read() or ""):trim()
assert(pass ~= "", "password is empty!")
-- compute user authorization
local token = base64.encode(user .. ":" .. pass)
token = hash.md5(bytes(token))
-- save to configs
local configs = assert(config.configs(), "configs not found!")
configs.tokens = configs.tokens or {}
if not hashset.from(configs.tokens):has(token) then
table.insert(configs.tokens, token)
else
cprint("User ${bright}%s${clear} has been added!", user)
return
end
config.save(configs)
cprint("Add user ${bright}%s${clear} ok!", user)
end
|
0 | repos/xmake/xmake/modules/private | repos/xmake/xmake/modules/private/service/service.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file main.lua
--
-- imports
import("core.base.option")
import("core.base.scheduler")
import("private.service.server_config", {alias = "config"})
import("private.service.remote_build.server", {alias = "remote_build_server"})
import("private.service.remote_cache.server", {alias = "remote_cache_server"})
import("private.service.distcc_build.server", {alias = "distcc_build_server"})
function _start_remote_build_server(...)
remote_build_server(...):runloop()
end
function _start_remote_cache_server(...)
remote_cache_server(...):runloop()
end
function _start_distcc_build_server(...)
distcc_build_server(...):runloop()
end
function main(daemon, ...)
if daemon then
config.load()
end
local starters = {}
if option.get("remote") then
table.insert(starters, _start_remote_build_server)
elseif option.get("distcc") then
table.insert(starters, _start_distcc_build_server)
elseif option.get("ccache") then
table.insert(starters, _start_remote_cache_server)
else
if config.get("remote_build") then
table.insert(starters, _start_remote_build_server)
end
if config.get("remote_cache") then
table.insert(starters, _start_remote_cache_server)
end
if config.get("distcc_build") then
table.insert(starters, _start_distcc_build_server)
end
end
for _, start_server in ipairs(starters) do
scheduler.co_start(start_server, daemon, ...)
end
end
|
0 | repos/xmake/xmake/modules/private | repos/xmake/xmake/modules/private/service/server_config.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file server_config.lua
--
-- imports
import("core.base.global")
import("core.base.base64")
import("core.base.bytes")
-- generate a token
function _generate_token()
return hash.md5(bytes(base64.encode(hash.uuid())))
end
-- generate a default config file
function _generate_configfile()
local filepath = configfile()
assert(not _g.configs and not os.isfile(filepath))
local servicedir = path.join(global.directory(), "service", "server")
local token = _generate_token()
print("generating the config file to %s ..", filepath)
cprint("an token(${bright yellow}%s${clear}) is generated, we can use this token to connect service.", token)
local configs = {
logfile = path.join(servicedir, "logs.txt"),
known_hosts = {
-- "127.0.0.1"
},
tokens = {
token
},
send_timeout = -1,
recv_timeout = -1,
remote_build = {
listen = "0.0.0.0:9691",
workdir = path.join(servicedir, "remote_build"),
},
remote_cache = {
listen = "0.0.0.0:9692",
workdir = path.join(servicedir, "remote_cache"),
},
distcc_build = {
listen = "0.0.0.0:9693",
workdir = path.join(servicedir, "distcc_build"),
toolchains = {
ndk = {
}
}
}
}
save(configs)
end
-- get config file path
function configfile()
return path.join(global.directory(), "service", "server.conf")
end
-- get all configs
function configs()
return _g.configs
end
-- get the given config, e.g. server_config.get("remote_build.listen")
function get(name)
local value = configs()
for _, key in ipairs(name:split('.', {plain = true})) do
if type(value) == "table" then
value = value[key]
else
value = nil
break
end
end
return value
end
-- load configs
function load()
if _g.configs == nil then
local filepath = configfile()
if not os.isfile(filepath) then
_generate_configfile()
end
assert(os.isfile(filepath), "%s not found!", filepath)
_g.configs = io.load(filepath)
end
end
-- save configs
function save(configs)
local filepath = configfile()
io.save(filepath, configs, {orderkeys = true})
end
|
0 | repos/xmake/xmake/modules/private | repos/xmake/xmake/modules/private/service/show_status.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file show_status.lua
--
-- imports
import("private.service.remote_build.client", {alias = "remote_build_client"})
function main()
local client = remote_build_client()
local status = client:status()
if status then
print("%s: connected", client)
print(status)
else
print("%s: disconnected", client)
end
end
|
0 | repos/xmake/xmake/modules/private/service | repos/xmake/xmake/modules/private/service/distcc_build/client_session.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file client_session.lua
--
-- imports
import("core.base.pipe")
import("core.base.bytes")
import("core.base.object")
import("core.base.global")
import("core.base.option")
import("core.base.socket")
import("core.base.hashset")
import("core.base.scheduler")
import("private.service.client_config", {alias = "config"})
import("private.service.message")
import("private.service.stream", {alias = "socket_stream"})
-- define module
local client_session = client_session or object()
-- init client session
function client_session:init(client, session_id, token, addr, port, opt)
opt = opt or {}
self._ID = session_id
self._ADDR = addr
self._PORT = port
self._TOKEN = token
self._CLIENT = client
self._SEND_TIMEOUT = opt.send_timeout and opt.send_timeout or -1
self._RECV_TIMEOUT = opt.recv_timeout and opt.recv_timeout or -1
self._CONNECT_TIMEOUT = opt.connect_timeout and opt.connect_timeout or -1
end
-- get client session id
function client_session:id()
return self._ID
end
-- get token
function client_session:token()
return self._TOKEN
end
-- get client
function client_session:client()
return self._CLIENT
end
-- get send timeout
function client_session:send_timeout()
return self._SEND_TIMEOUT
end
-- get recv timeout
function client_session:recv_timeout()
return self._RECV_TIMEOUT
end
-- get connect timeout
function client_session:connect_timeout()
return self._CONNECT_TIMEOUT
end
-- server unreachable?
function client_session:is_unreachable()
return self._UNREACHABLE
end
-- get stream
function client_session:stream()
local stream = self._STREAM
if stream == nil then
local addr = self._ADDR
local port = self._PORT
local sock = socket.connect(addr, port, {timeout = self:connect_timeout()})
if not sock then
self._UNREACHABLE = true
raise("%s: server unreachable!", self)
end
stream = socket_stream(sock, {send_timeout = self:send_timeout(), recv_timeout = self:recv_timeout()})
self._STREAM = stream
end
return stream
end
-- open session
function client_session:open(host_status)
assert(not self:is_opened(), "%s: has been opened!", self)
self._OPENED = true
self._HOST_STATUS = host_status
end
-- close session
function client_session:close()
self._OPENED = false
end
-- is opened?
function client_session:is_opened()
return self._OPENED
end
-- get host status
function client_session:host_status()
return self._HOST_STATUS
end
-- run compilation job
function client_session:compile(sourcefile, objectfile, cppfile, cppflags, opt)
assert(self:is_opened(), "%s: has been not opened!", self)
local ok = false
local errors
local tool = opt.tool
local toolname = tool:name()
local toolkind = tool:kind()
local plat = tool:plat()
local arch = tool:arch()
local cachekey = opt.cachekey
local toolchain = tool:toolchain():name()
local stream = self:stream()
local host_status = self:host_status()
local outdata, errdata
if stream:send_msg(message.new_compile(self:id(), toolname, toolkind, plat, arch, toolchain,
cppflags, path.filename(sourcefile), {token = self:token(), cachekey = cachekey})) and
stream:send_file(cppfile, {compress = os.filesize(cppfile) > 4096}) and stream:flush() then
local recv = stream:recv_file(objectfile, {timeout = -1})
if recv ~= nil then
local msg = stream:recv_msg()
if msg then
if msg:success() then
local body = msg:body()
outdata = body.outdata
errdata = body.errdata
host_status.cpurate = body.cpurate
host_status.memrate = body.memrate
ok = true
else
errors = msg:errors()
end
end
else
errors = "recv object file failed!"
end
end
os.tryrm(cppfile)
assert(ok, "%s: %s", self, errors or "unknown errors!")
return outdata, errdata
end
-- get work directory
function client_session:workdir()
return path.join(self:server():workdir(), "sessions", self:id())
end
function client_session:__tostring()
return string.format("<session %s: %s>", self:id(), self._ADDR)
end
function main(client, session_id, token, addr, port, opt)
local instance = client_session()
instance:init(client, session_id, token, addr, port, opt)
return instance
end
|
0 | repos/xmake/xmake/modules/private/service | repos/xmake/xmake/modules/private/service/distcc_build/server.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file server.lua
--
-- imports
import("core.base.global")
import("private.service.server_config", {alias = "config"})
import("private.service.message")
import("private.service.server")
import("private.service.distcc_build.server_session")
import("lib.detect.find_tool")
-- define module
local distcc_build_server = distcc_build_server or server()
local super = distcc_build_server:class()
-- init server
function distcc_build_server:init(daemon)
super.init(self, daemon)
-- init address
local address = assert(config.get("distcc_build.listen"), "config(distcc_build.listen): not found!")
super.address_set(self, address)
-- init handler
super.handler_set(self, self._on_handle)
-- init sessions
self._SESSIONS = {}
-- init timeout
self._SEND_TIMEOUT = config.get("distcc_build.send_timeout") or config.get("send_timeout") or -1
self._RECV_TIMEOUT = config.get("distcc_build.recv_timeout") or config.get("recv_timeout") or -1
end
-- get class
function distcc_build_server:class()
return distcc_build_server
end
-- get work directory
function distcc_build_server:workdir()
local workdir = config.get("distcc_build.workdir")
if not workdir then
workdir = path.join(global.directory(), "service", "server", "distcc_build")
end
return workdir
end
-- on handle message
function distcc_build_server:_on_handle(stream, msg)
local session_id = msg:session_id()
local session = self:_session(session_id)
vprint("%s: %s: <session %s>: on handle message(%d)", self, stream:sock(), session_id, msg:code())
vprint(msg:body())
session:stream_set(stream)
local respmsg = msg:clone()
local session_errs
local session_ok = try
{
function()
if self:need_verfiy() then
local ok, errors = self:verify_user(msg:token(), stream:sock():peeraddr())
if not ok then
session_errs = errors
return false
end
end
if msg:is_connect() then
session:open(respmsg)
else
assert(session:is_connected(), "session has not been connected!")
if msg:is_compile() then
local ok, errors = session:compile(respmsg)
if not ok then
session_errs = errors
return false
end
elseif msg:is_clean() then
session:clean()
end
end
return true
end,
catch
{
function (errors)
if errors then
session_errs = tostring(errors)
end
end
}
}
respmsg:status_set(session_ok)
if not session_ok and session_errs then
respmsg:errors_set(session_errs)
vprint(session_errs)
end
local ok = stream:send_msg(respmsg) and stream:flush()
vprint("%s: %s: <session %s>: send %s", self, stream:sock(), session_id, ok and "ok" or "failed")
end
-- get session
function distcc_build_server:_session(session_id)
local session = self._SESSIONS[session_id]
if not session then
session = server_session(self, session_id)
self._SESSIONS[session_id] = session
end
return session
end
-- close session
function distcc_build_server:_session_close(session_id)
self._SESSIONS[session_id] = nil
end
function distcc_build_server:__tostring()
return "<distcc_build_server>"
end
function main(daemon)
local instance = distcc_build_server()
instance:init(daemon ~= nil)
return instance
end
|
0 | repos/xmake/xmake/modules/private/service | repos/xmake/xmake/modules/private/service/distcc_build/client.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file client.lua
--
-- imports
import("core.base.bytes")
import("core.base.base64")
import("core.base.socket")
import("core.base.option")
import("core.base.scheduler")
import("core.project.policy")
import("core.project.config", {alias = "project_config"})
import("lib.detect.find_tool")
import("private.service.client_config", {alias = "config"})
import("private.service.message")
import("private.service.client")
import("private.cache.build_cache")
import("private.service.distcc_build.client_session")
import("private.service.stream", {alias = "socket_stream"})
-- define module
local distcc_build_client = distcc_build_client or client()
local super = distcc_build_client:class()
-- init client
function distcc_build_client:init()
super.init(self)
-- init hosts
local hosts = assert(config.get("distcc_build.hosts"), "config(distcc_build.hosts): not found!")
self:hosts_set(hosts)
-- get project directory
local projectdir = os.projectdir()
local projectfile = os.projectfile()
if projectfile and os.isfile(projectfile) and projectdir then
self._PROJECTDIR = projectdir
self._WORKDIR = path.join(project_config.directory(), "service", "distcc_build")
else
raise("we need to enter a project directory with xmake.lua first!")
end
-- init timeout
self._SEND_TIMEOUT = config.get("distcc_build.send_timeout") or config.get("send_timeout") or -1
self._RECV_TIMEOUT = config.get("distcc_build.recv_timeout") or config.get("recv_timeout") or -1
self._CONNECT_TIMEOUT = config.get("distcc_build.connect_timeout") or config.get("connect_timeout") or 10000
end
-- get class
function distcc_build_client:class()
return distcc_build_client
end
-- get the client hosts
function distcc_build_client:hosts()
return self._HOSTS
end
-- set the client hosts
function distcc_build_client:hosts_set(hosts)
local hostinfos = {}
for _, host in ipairs(hosts) do
local hostinfo = {}
local address = assert(host.connect, "connect address not found in hosts configuration!")
local addr, port, user = self:address_parse(address)
if addr and port then
hostinfo.addr = addr
hostinfo.port = port
hostinfo.user = user
hostinfo.token = host.token
hostinfo.njob = host.njob
table.insert(hostinfos, hostinfo)
end
end
self._HOSTS = hostinfos
end
-- get the status of client hosts
function distcc_build_client:hosts_status()
local hosts_status = self._HOSTS_STATUS
if hosts_status == nil then
hosts_status = table.copy(self:status().hosts)
for _, host_status in pairs(hosts_status) do
self:_host_status_update(host_status)
end
self._HOSTS_STATUS = hosts_status
end
return hosts_status
end
-- connect to the distcc server
function distcc_build_client:connect()
if self:is_connected() then
print("%s: has been connected!", self)
return
end
-- do connect
local hosts = self:hosts()
assert(hosts and #hosts > 0, "hosts not found!")
local group_name = tostring(self) .. "/connect"
scheduler.co_group_begin(group_name, function ()
for _, host in ipairs(hosts) do
scheduler.co_start(self._connect_host, self, host)
end
end)
scheduler.co_group_wait(group_name)
-- all hosts are connected?
local connected = true
for _, host in ipairs(hosts) do
if not self:_is_connected(host.addr, host.port) then
connected = false
end
end
-- update status
local status = self:status()
status.connected = connected
self:status_save()
end
-- disconnect server
function distcc_build_client:disconnect()
if not self:is_connected() then
print("%s: has been disconnected!", self)
return
end
-- do disconnect
local hosts = self:hosts()
assert(hosts and #hosts > 0, "hosts not found!")
for _, host in ipairs(hosts) do
self:_disconnect_host(host)
end
-- all hosts are connected?
local connected = true
for _, host in ipairs(hosts) do
if not self:_is_connected(host.addr, host.port) then
connected = false
end
end
-- update status
local status = self:status()
status.connected = connected
self:status_save()
end
-- is connected?
function distcc_build_client:is_connected()
return self:status().connected
end
-- get max jobs count
function distcc_build_client:maxjobs()
local maxjobs = self._MAXJOBS
if maxjobs == nil then
maxjobs = 0
for _, host in pairs(self:status().hosts) do
maxjobs = maxjobs + host.njob
end
self._MAXJOBS = maxjobs
end
return maxjobs or 0
end
-- get free jobs count
function distcc_build_client:freejobs()
local maxjobs = self:maxjobs()
if maxjobs > 0 then
local running = (self._RUNNING or 0)
if running > maxjobs then
running = maxjobs
end
return maxjobs - running
end
return 0
end
-- has free jobs?
function distcc_build_client:has_freejobs()
return self:freejobs() > 0
end
-- clean server files
function distcc_build_client:clean()
if not self:is_connected() then
print("%s: has been disconnected!", self)
return
end
-- do disconnect
local hosts = self:hosts()
assert(hosts and #hosts > 0, "hosts not found!")
local group_name = tostring(self) .. "/clean"
scheduler.co_group_begin(group_name, function ()
for _, host in ipairs(hosts) do
scheduler.co_start(self._clean_host, self, host)
end
end)
scheduler.co_group_wait(group_name)
end
-- run compilation job
function distcc_build_client:compile(program, argv, opt)
-- get free host
local host = assert(self:_get_freehost(), "free host not found!")
-- lock this host
self:_host_status_lock(host)
-- open the host session
local session = assert(self:_host_status_session_open(host), "open session failed!")
-- do preprocess
opt = opt or {}
local preprocess = assert(opt.preprocess, "preprocessor not found!")
local cppinfo = preprocess(program, argv, opt)
local build_in_local = false
if cppinfo then
-- get objectfile from the build cache first
local cached = false
local cachekey
if build_cache.is_enabled(opt.target) then
cachekey = build_cache.cachekey(program, cppinfo, opt.envs)
local objectfile_cached, objectfile_infofile = build_cache.get(cachekey)
if objectfile_cached then
os.cp(objectfile_cached, cppinfo.objectfile)
-- we need to update mtime for incremental compilation
-- @see https://github.com/xmake-io/xmake/issues/2620
os.touch(cppinfo.objectfile, {mtime = os.time()})
-- we need to get outdata/errdata to show warnings,
-- @see https://github.com/xmake-io/xmake/issues/2452
if objectfile_infofile and os.isfile(objectfile_infofile) then
local extrainfo = io.load(objectfile_infofile)
cppinfo.outdata = extrainfo.outdata
cppinfo.errdata = extrainfo.errdata
end
cached = true
end
end
-- do distcc compilation
if not cached then
-- we just compile the large preprocessed file in remote
if os.filesize(cppinfo.cppfile) > 4096 and not session:is_unreachable() then
local compile_fallback = opt.compile_fallback
if compile_fallback then
local ok = try
{
function ()
local outdata, errdata = session:compile(cppinfo.sourcefile, cppinfo.objectfile, cppinfo.cppfile, cppinfo.cppflags,
table.join(opt, {cachekey = cachekey}))
cppinfo.outdata = outdata
cppinfo.errdata = errdata
return true
end,
catch
{
function (errors)
if errors and policy.build_warnings() then
cprint("${color.warning}fallback to the local compiler, %s", tostring(errors))
end
end
}
}
if not ok then
-- we fallback to compile original source file if compiling preprocessed file fails.
-- https://github.com/xmake-io/xmake/issues/2467
local outdata, errdata = compile_fallback()
cppinfo.outdata = outdata
cppinfo.errdata = errdata
end
else
local outdata, errdata = session:compile(cppinfo.sourcefile, cppinfo.objectfile, cppinfo.cppfile, cppinfo.cppflags,
table.join(opt, {cachekey = cachekey}))
cppinfo.outdata = outdata
cppinfo.errdata = errdata
end
if cachekey then
local extrainfo
if cppinfo.outdata and #cppinfo.outdata ~= 0 then
extrainfo = extrainfo or {}
extrainfo.outdata = cppinfo.outdata
end
if cppinfo.errdata and #cppinfo.errdata ~= 0 then
extrainfo = extrainfo or {}
extrainfo.errdata = cppinfo.errdata
end
build_cache.put(cachekey, cppinfo.objectfile, extrainfo)
end
else
build_in_local = true
end
end
end
-- close session
self:_host_status_session_close(host, session)
-- unlock this host
self:_host_status_unlock(host)
-- build in local
if build_in_local then
if cppinfo and build_in_local then
local compile = assert(opt.compile, "compiler not found!")
local compile_fallback = opt.compile_fallback
if compile_fallback then
local ok = try {function () compile(program, cppinfo, opt); return true end}
if not ok then
-- we fallback to compile original source file if compiling preprocessed file fails.
-- https://github.com/xmake-io/xmake/issues/2467
local outdata, errdata = compile_fallback()
cppinfo.outdata = outdata
cppinfo.errdata = errdata
end
else
compile(program, cppinfo, opt)
end
if build_cache.is_enabled(opt.target) then
local cachekey = build_cache.cachekey(program, cppinfo, opt.envs)
if cachekey then
local extrainfo
if cppinfo.outdata and #cppinfo.outdata ~= 0 then
extrainfo = extrainfo or {}
extrainfo.outdata = cppinfo.outdata
end
if cppinfo.errdata and #cppinfo.errdata ~= 0 then
extrainfo = extrainfo or {}
extrainfo.errdata = cppinfo.errdata
end
build_cache.put(cachekey, cppinfo.objectfile, extrainfo)
end
end
end
end
return cppinfo
end
-- get the status
function distcc_build_client:status()
local status = self._STATUS
local statusfile = self:statusfile()
if not status then
if os.isfile(statusfile) then
status = io.load(statusfile)
end
status = status or {}
self._STATUS = status
end
return status
end
-- save status
function distcc_build_client:status_save()
io.save(self:statusfile(), self:status())
end
-- get the status file
function distcc_build_client:statusfile()
return path.join(self:workdir(), "status.txt")
end
-- get the project directory
function distcc_build_client:projectdir()
return self._PROJECTDIR
end
-- get working directory
function distcc_build_client:workdir()
return self._WORKDIR
end
-- get free host
function distcc_build_client:_get_freehost()
local max_weight = -1
local host
if self:has_freejobs() then
for _, host_status in pairs(self:hosts_status()) do
if host_status.freejobs > 0 and host_status.weight > max_weight then
max_weight = host_status.weight
host = host_status
end
end
end
return host
end
-- update the host status
function distcc_build_client:_host_status_update(host_status)
local running = host_status.running or 0
if running > host_status.njob then
running = host_status.njob
end
if running < 0 then
running = 0
end
host_status.running = running
host_status.freejobs = host_status.njob - host_status.running
host_status.weight = host_status.freejobs * (1.0 - (host_status.cpurate or 0))
if host_status.memrate and host_status.memrate > 0.9 then
host_status.weight = host_status.weight * (1.0 - (host_status.memrate or 0))
end
end
-- lock host status
function distcc_build_client:_host_status_lock(host_status)
-- update the host status
host_status.running = host_status.running + 1
self:_host_status_update(host_status)
-- update the total running status
local running = (self._RUNNING or 0) + 1
if running > self:maxjobs() then
running = self:maxjobs()
end
self._RUNNING = running
end
-- unlock host status
function distcc_build_client:_host_status_unlock(host_status)
-- update the host status
host_status.running = host_status.running - 1
self:_host_status_update(host_status)
-- update the total running status
local running = self._RUNNING - 1
if running < 0 then
running = 0
end
self._RUNNING = running
end
-- open host session
function distcc_build_client:_host_status_session_open(host_status)
host_status.sessions = host_status.sessions or {}
host_status.free_sessions = host_status.free_sessions or {}
local sessions = host_status.sessions
local free_sessions = host_status.free_sessions
if #free_sessions > 0 then
local session = free_sessions[#free_sessions]
if session and not session:is_opened() then
table.remove(free_sessions)
session:open(host_status)
return session
end
end
local njob = host_status.njob
for i = 1, njob do
local session = host_status.sessions[i]
if not session then
session = client_session(self, host_status.session_id, host_status.token, host_status.addr, host_status.port,
{send_timeout = self:send_timeout(), recv_timeout = self:recv_timeout(), connect_timeout = self:connect_timeout()})
host_status.sessions[i] = session
session:open(host_status)
return session
elseif not session:is_opened() then
session:open(host_status)
return session
end
end
end
-- close session
function distcc_build_client:_host_status_session_close(host_status, session)
host_status.free_sessions = host_status.free_sessions or {}
session:close()
table.insert(host_status.free_sessions, session)
end
-- get the session id, only for unique project
function distcc_build_client:_session_id(addr, port)
local hosts = self:status().hosts
if hosts then
local host = hosts[addr .. ":" .. port]
if host then
return host.session_id
end
end
return hash.uuid(option.get("session")):split("-", {plain = true})[1]:lower()
end
-- is connected for the given host
function distcc_build_client:_is_connected(addr, port)
local hosts = self:status().hosts
if hosts then
local host = hosts[addr .. ":" .. port]
if host then
return host.connected
end
end
end
-- connect to the host
function distcc_build_client:_connect_host(host)
local addr = host.addr
local port = host.port
if self:_is_connected(addr, port) then
print("%s: %s:%d has been connected!", self, addr, port)
return
end
-- Do we need user authorization?
local user = host.user
local token = host.token
if not token and user then
-- get user password
cprint("Please input user ${bright}%s${clear} password to connect <%s:%d>:", user, addr, port)
io.flush()
local pass = (io.read() or ""):trim()
assert(pass ~= "", "password is empty!")
-- compute user authorization
token = base64.encode(self:user() .. ":" .. pass)
token = hash.md5(bytes(token))
end
-- do connect
local sock = assert(socket.connect(addr, port, {timeout = self:connect_timeout()}), "%s: server unreachable!", self)
local session_id = self:_session_id(addr, port)
local ok = false
local errors
local ncpu, njob
print("%s: connect %s:%d ..", self, addr, port)
if sock then
local stream = socket_stream(sock, {send_timeout = self:send_timeout(), recv_timeout = self:recv_timeout()})
if stream:send_msg(message.new_connect(session_id, {token = token})) and stream:flush() then
local msg = stream:recv_msg()
if msg then
local body = msg:body()
vprint(body)
if msg:success() then
ncpu = body.ncpu
njob = body.njob
ok = true
else
errors = msg:errors()
end
end
end
end
if ok then
print("%s: %s:%d connected!", self, addr, port)
else
print("%s: connect %s:%d failed, %s", self, addr, port, errors or "unknown")
end
-- update status
local status = self:status()
status.hosts = status.hosts or {}
status.hosts[addr .. ":" .. port] = {
addr = addr, port = port, token = token,
connected = ok, session_id = session_id,
ncpu = ncpu, njob = host.njob or njob}
self:status_save()
end
-- disconnect from the host
function distcc_build_client:_disconnect_host(host)
local addr = host.addr
local port = host.port
if not self:_is_connected(addr, port) then
print("%s: %s:%d has been disconnected!", self, addr, port)
return
end
-- update status
local status = self:status()
status.hosts = status.hosts or {}
local host_status = status.hosts[addr .. ":" .. port]
if host_status then
host_status.token = nil
host_status.connected = false
end
self:status_save()
print("%s: %s:%d disconnected!", self, addr, port)
end
-- clean file for the host
function distcc_build_client:_clean_host(host)
local addr = host.addr
local port = host.port
if not self:_is_connected(addr, port) then
print("%s: %s:%d has been disconnected!", self, addr, port)
return
end
-- do clean
local token = host.token
local sock = socket.connect(addr, port, {timeout = self:connect_timeout()})
local session_id = self:_session_id(addr, port)
local errors
local ok = false
print("%s: clean files in %s:%d ..", self, addr, port)
if sock then
local stream = socket_stream(sock, {send_timeout = self:send_timeout(), recv_timeout = self:recv_timeout()})
if stream:send_msg(message.new_clean(session_id, {token = token})) and stream:flush() then
local msg = stream:recv_msg()
if msg then
vprint(msg:body())
if msg:success() then
ok = true
else
errors = msg:errors()
end
end
end
else
-- server unreachable, but we still disconnect it.
wprint("%s: server unreachable!", self)
ok = true
end
if ok then
print("%s: %s:%d clean files ok!", self, addr, port)
else
print("%s: clean files %s:%d failed, %s", self, addr, port, errors or "unknown")
end
end
-- is connected? we cannot depend on client:init when run action
function is_connected()
local connected = _g.connected
if connected == nil then
-- the current process is in service? we cannot enable it
if os.getenv("XMAKE_IN_SERVICE") then
connected = false
end
if connected == nil then
local projectdir = os.projectdir()
local projectfile = os.projectfile()
if projectfile and os.isfile(projectfile) and projectdir then
local workdir = path.join(project_config.directory(), "service", "distcc_build")
local statusfile = path.join(workdir, "status.txt")
if os.isfile(statusfile) then
local status = io.load(statusfile)
if status and status.connected then
connected = true
end
end
end
end
connected = connected or false
_g.connected = connected
end
return connected
end
-- we can run distcc job?
function is_distccjob()
if is_connected() then
local co_running = scheduler.co_running()
if co_running then
return co_running:data("distcc.distccjob")
end
end
end
-- new a client instance
function new()
local instance = distcc_build_client()
instance:init()
return instance
end
-- get the singleton
function singleton()
local instance = _g.singleton
if not instance then
config.load()
instance = new()
_g.singleton = instance
end
return instance
end
function main()
return new()
end
|
0 | repos/xmake/xmake/modules/private/service | repos/xmake/xmake/modules/private/service/distcc_build/server_session.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file server_session.lua
--
-- imports
import("core.base.pipe")
import("core.base.bytes")
import("core.base.object")
import("core.base.global")
import("core.base.option")
import("core.base.hashset")
import("core.base.scheduler")
import("core.tool.toolchain")
import("core.cache.memcache")
import("private.tools.vstool")
import("private.service.server_config", {alias = "config"})
import("private.service.message")
-- define module
local server_session = server_session or object()
-- init server session
function server_session:init(server, session_id)
self._ID = session_id
self._SERVER = server
end
-- get server session id
function server_session:id()
return self._ID
end
-- get server
function server_session:server()
return self._SERVER
end
-- open server session
function server_session:open(respmsg)
local body = respmsg:body()
body.ncpu = os.cpuinfo().ncpu
body.njob = os.default_njob()
if not self:is_connected() then
local status = self:status()
status.connected = true
status.session_id = self:id()
self:status_save()
end
end
-- close server session
function server_session:close()
if not self:is_connected() then
return
end
-- update status
local status = self:status()
status.connected = false
status.session_id = self:id()
self:status_save()
end
-- do clean
function server_session:clean()
vprint("%s: clean files in %s ..", self, self:workdir())
os.tryrm(self:buildir())
os.tryrm(self:cachedir())
vprint("%s: clean files ok", self)
end
-- do compile
function server_session:compile(respmsg)
-- recv source file
local body = respmsg:body()
local stream = self:stream()
local cachekey = body.cachekey
local sourcename = body.sourcename
local sourcedir = path.join(self:buildir(), (hash.uuid4():gsub("-", "")))
local sourcefile = path.join(sourcedir, sourcename)
local objectfile = (cachekey and path.join(self:cachedir(), cachekey:sub(1, 2), cachekey) or sourcefile) .. ".o"
local objectfile_infofile = objectfile .. ".txt"
if not stream:recv_file(sourcefile) then
raise("recv %s failed!", sourcename)
end
-- do compile
local errors
local ok
local outdata, errdata
if not (cachekey and os.isfile(objectfile)) then -- no cached object file?
ok = try
{
function ()
local flags = body.flags
local toolname = body.toolname
local compile = assert(self["_" .. toolname .. "_compile"], "%s: compiler(%s) is not supported!", self, toolname)
local objectdir = path.directory(objectfile)
if not os.isdir(objectdir) then
os.mkdir(objectdir)
end
outdata, errdata = compile(self, toolname, flags, sourcefile, objectfile, body)
local extrainfo
if outdata and #outdata ~= 0 then
extrainfo = extrainfo or {}
extrainfo.outdata = outdata
end
if errdata and #errdata ~= 0 then
extrainfo = extrainfo or {}
extrainfo.errdata = errdata
end
if extrainfo then
io.save(objectfile_infofile, extrainfo)
end
return os.isfile(objectfile)
end,
catch
{
function (errs)
errors = tostring(errs)
end
}
}
if ok then
vprint("send compiled object file %s ..", objectfile)
end
else
vprint("send cached object file %s ..", objectfile)
if os.isfile(objectfile_infofile) then
local extrainfo = io.load(objectfile_infofile)
outdata = extrainfo.outdata
errdata = extrainfo.errdata
end
ok = true
end
-- send object file
if ok then
if not stream:send_file(objectfile, {compress = os.filesize(objectfile) > 4096}) then
raise("send %s failed!", objectfile)
end
body.outdata = outdata
body.errdata = errdata
else
if not stream:send_emptydata() then
raise("send empty data failed!")
end
end
-- send current server status
body.cpurate = os.cpuinfo("usagerate")
body.memrate = os.meminfo("usagerate")
-- remove files
os.tryrm(sourcefile)
if not cachekey then
os.tryrm(objectfile)
end
return ok, errors
end
-- set stream
function server_session:stream_set(stream)
self._STREAM = stream
end
-- get stream
function server_session:stream()
return self._STREAM
end
-- get work directory
function server_session:workdir()
return path.join(self:server():workdir(), "sessions", self:id())
end
-- get build directory
function server_session:buildir()
return path.join(self:workdir(), "build")
end
-- get cache directory
function server_session:cachedir()
return path.join(self:workdir(), "cache")
end
-- is connected?
function server_session:is_connected()
return self:status().connected
end
-- get the status
function server_session:status()
local status = self._STATUS
local statusfile = self:statusfile()
if not status then
if os.isfile(statusfile) then
status = io.load(statusfile)
end
status = status or {}
self._STATUS = status
end
return status
end
-- save status
function server_session:status_save()
io.save(self:statusfile(), self:status())
end
-- get status file
function server_session:statusfile()
return path.join(self:workdir(), "status.txt")
end
-- get cache
function server_session:_cache()
return memcache.cache("distcc_build_server.session")
end
-- get tool
function server_session:_tool(name, opt)
opt = opt or {}
local plat = opt.plat
local arch = opt.arch
local toolkind = opt.toolkind
local cachekey = name .. (plat or "") .. (arch or "") .. toolkind
local cacheinfo = self:_cache():get(cachekey)
if not cacheinfo then
local toolchain_configs = (config.get("distcc_build.toolchains") or {})[name]
local toolchain_inst = toolchain.load(name, table.join({plat = plat, arch = arch}, toolchain_configs))
if toolchain_inst:check() then
local program, toolname = toolchain_inst:tool(toolkind)
assert(program, "%s/%s not found!", name, toolkind)
cacheinfo = {program, toolname, toolchain_inst:runenvs()}
self:_cache():set(cachekey, cacheinfo)
else
raise("toolchain(%s) not found!", name)
end
end
return cacheinfo[1], cacheinfo[2], cacheinfo[3]
end
-- do compile job for gcc
function server_session:_gcc_compile(toolname, flags, sourcefile, objectfile, opt)
local program, toolname_real, runenvs = self:_tool(opt.toolchain, opt)
assert(toolname_real == toolname, "toolname is not matched, %s != %s", toolname, toolname_real)
return os.iorunv(program, table.join(flags, "-o", objectfile, sourcefile), {envs = runenvs})
end
-- do compile job for g++
function server_session:_gxx_compile(toolname, flags, sourcefile, objectfile, opt)
return self:_gcc_compile(toolname, flags, sourcefile, objectfile, opt)
end
-- do compile job for clang
function server_session:_clang_compile(toolname, flags, sourcefile, objectfile, opt)
return self:_gcc_compile(toolname, flags, sourcefile, objectfile, opt)
end
-- do compile job for clang++
function server_session:_clangxx_compile(toolname, flags, sourcefile, objectfile, opt)
return self:_gcc_compile(toolname, flags, sourcefile, objectfile, opt)
end
-- do compile job for cl
function server_session:_cl_compile(toolname, flags, sourcefile, objectfile, opt)
local program, toolname_real, runenvs = self:_tool(opt.toolchain, opt)
assert(toolname_real == toolname, "toolname is not matched, %s != %s", toolname, toolname_real)
return vstool.iorunv(program, winos.cmdargv(table.join(flags, "-Fo" .. objectfile, sourcefile)), {envs = runenvs})
end
function server_session:__tostring()
return string.format("<session %s>", self:id())
end
function main(server, session_id)
local instance = server_session()
instance:init(server, session_id)
return instance
end
|
0 | repos/xmake/xmake/modules/private/service | repos/xmake/xmake/modules/private/service/remote_build/filesync.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file filesync.lua
--
-- imports
import("core.base.object")
-- define module
local filesync = filesync or object()
-- init filesync
function filesync:init(rootdir, manifest_file)
self._ROOTDIR = rootdir
self._MANIFEST_FILE = manifest_file
end
-- get root directory
function filesync:rootdir()
return self._ROOTDIR
end
-- get ignore files
function filesync:ignorefiles()
local ignorefiles = self._IGNOREFILES
if not ignorefiles then
ignorefiles = {}
self:_ignorefiles_load(ignorefiles)
self._IGNOREFILES = ignorefiles
end
return ignorefiles
end
-- add ignore files
function filesync:ignorefiles_add(...)
table.join2(self:ignorefiles(), ...)
end
-- get manifest
function filesync:manifest()
local manifest = self._MANIFEST
if not manifest then
local manifest_file = self:manifest_file()
if manifest_file and os.isfile(manifest_file) then
manifest = io.load(manifest_file)
end
manifest = manifest or {}
self._MANIFEST = manifest
end
return manifest
end
-- save manifest file
function filesync:manifest_save()
local manifest_file = self:manifest_file()
if manifest_file then
io.save(manifest_file, self:manifest())
end
end
-- get manifest file
function filesync:manifest_file()
return self._MANIFEST_FILE
end
-- do snapshot, it will re-scan all and update to manifest file
function filesync:snapshot()
local rootdir = self:rootdir()
assert(rootdir and os.isdir(rootdir), "get snapshot %s failed, rootdir not found!", rootdir)
local manifest = {}
local manifest_old = self:manifest()
local ignorefiles = self:ignorefiles()
if ignorefiles then
ignorefiles = "|" .. table.concat(ignorefiles, "|")
end
local count = 0
for _, filepath in ipairs(os.files(path.join(rootdir, "**" .. ignorefiles))) do
local fileitem = path.relative(filepath, rootdir)
if fileitem then
-- we should always use '/' in path key for supporting linux & windows
-- https://github.com/xmake-io/xmake/issues/2488
if is_host("windows") then
fileitem = fileitem:gsub("\\", "/")
end
local manifest_info = manifest_old[fileitem]
local mtime = os.mtime(filepath)
if not manifest_info or not manifest_info.mtime or mtime > manifest_info.mtime then
manifest[fileitem] = {sha256 = hash.sha256(filepath), mtime = mtime}
else
manifest[fileitem] = manifest_info
end
count = count + 1
end
end
self._MANIFEST = manifest
self:manifest_save()
return manifest, count
end
-- update file
function filesync:update(fileitem, filepath, sha256)
local mtime = os.mtime(filepath)
local manifest = self:manifest()
sha256 = sha256 or hash.sha256(filepath)
manifest[fileitem] = {sha256 = sha256, mtime = mtime}
end
-- remove file
function filesync:remove(fileitem)
local manifest = self:manifest()
manifest[fileitem] = nil
end
-- load ignore files from .gitignore files
function filesync:_ignorefiles_load(ignorefiles)
local rootdir = self:rootdir()
local gitignore_files = os.files(path.join(rootdir, "**", ".gitignore"))
if os.isfile(path.join(rootdir, ".gitignore")) then
table.insert(gitignore_files, path.join(rootdir, ".gitignore"))
end
for _, gitignore_file in ipairs(gitignore_files) do
local gitroot = path.directory(gitignore_file)
local gitignore = io.open(gitignore_file, "r")
for line in gitignore:lines() do
line = line:trim()
if #line > 0 and not line:startswith("#") then
local filepath = path.join(gitroot, line)
local pattern = path.relative(filepath, rootdir)
if pattern then
if line:endswith(path.sep()) or os.isdir(line) then
table.insert(ignorefiles, path.join(pattern, "**"))
elseif os.isfile(line) then
table.insert(ignorefiles, pattern)
elseif line:find("*.", 1, true) then
table.insert(ignorefiles, (pattern:gsub("%*%.", "**.")))
else
table.insert(ignorefiles, pattern)
table.insert(ignorefiles, path.join(pattern, "**"))
end
end
end
end
gitignore:close()
end
end
function main(rootdir, manifest_file)
local instance = filesync()
instance:init(rootdir, manifest_file)
return instance
end
|
0 | repos/xmake/xmake/modules/private/service | repos/xmake/xmake/modules/private/service/remote_build/server.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file server.lua
--
-- imports
import("core.base.global")
import("private.service.server_config", {alias = "config"})
import("private.service.message")
import("private.service.server")
import("private.service.remote_build.server_session")
import("private.service.remote_build.filesync", {alias = "new_filesync"})
import("lib.detect.find_tool")
-- define module
local remote_build_server = remote_build_server or server()
local super = remote_build_server:class()
-- init server
function remote_build_server:init(daemon)
super.init(self, daemon)
-- init address
local address = assert(config.get("remote_build.listen"), "config(remote_build.listen): not found!")
super.address_set(self, address)
-- init handler
super.handler_set(self, self._on_handle)
-- init sessions
self._SESSIONS = {}
-- init timeout
self._SEND_TIMEOUT = config.get("remote_build.send_timeout") or config.get("send_timeout") or -1
self._RECV_TIMEOUT = config.get("remote_build.recv_timeout") or config.get("recv_timeout") or -1
-- init xmake filesync
local xmake_filesync = new_filesync(self:xmake_sourcedir(), path.join(self:workdir(), "xmakesrc_manifest.txt"))
xmake_filesync:ignorefiles_add(".git/**")
self._XMAKE_FILESYNC = xmake_filesync
end
-- get class
function remote_build_server:class()
return remote_build_server
end
-- get work directory
function remote_build_server:workdir()
local workdir = config.get("remote_build.workdir")
if not workdir then
workdir = path.join(global.directory(), "service", "server", "remote_build")
end
return workdir
end
-- get xmake sourcedir directory
function remote_build_server:xmake_sourcedir()
return path.join(self:workdir(), "xmake_source")
end
-- get filesync for xmakesrc
function remote_build_server:_xmake_filesync()
return self._XMAKE_FILESYNC
end
-- on handle message
function remote_build_server:_on_handle(stream, msg)
local session_id = msg:session_id()
local session = self:_session(session_id)
vprint("%s: %s: <session %s>: on handle message(%d)", self, stream:sock(), session_id, msg:code())
vprint(msg:body())
session:stream_set(stream)
local respmsg = msg:clone()
local session_errs
local session_ok = try
{
function()
if self:need_verfiy() then
local ok, errors = self:verify_user(msg:token(), stream:sock():peeraddr())
if not ok then
session_errs = errors
return false
end
end
if msg:is_connect() then
session:open()
else
assert(session:is_connected(), "session has not been connected!")
if msg:is_diff() then
session:diff(respmsg)
elseif msg:is_sync() then
session:sync(respmsg)
elseif msg:is_pull() then
session:pull(respmsg)
elseif msg:is_clean() then
session:clean(respmsg)
elseif msg:is_runcmd() then
session:runcmd(respmsg)
end
end
return true
end,
catch
{
function (errors)
if errors then
session_errs = tostring(errors)
vprint(session_errs)
end
end
}
}
respmsg:status_set(session_ok)
if not session_ok and session_errs then
respmsg:errors_set(session_errs)
end
local ok = stream:send_msg(respmsg) and stream:flush()
vprint("%s: %s: <session %s>: send %s", self, stream:sock(), session_id, ok and "ok" or "failed")
end
-- get session
function remote_build_server:_session(session_id)
local session = self._SESSIONS[session_id]
if not session then
session = server_session(self, session_id)
self._SESSIONS[session_id] = session
end
return session
end
-- close session
function remote_build_server:_session_close(session_id)
self._SESSIONS[session_id] = nil
end
function remote_build_server:__tostring()
return "<remote_build_server>"
end
function main(daemon)
local instance = remote_build_server()
instance:init(daemon ~= nil)
return instance
end
|
0 | repos/xmake/xmake/modules/private/service | repos/xmake/xmake/modules/private/service/remote_build/action.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file action.lua
--
-- imports
import("private.service.client_config", {alias = "config"})
import("private.service.remote_build.client", {alias = "remote_build_client"})
-- is enabled?
function enabled()
return remote_build_client.is_connected()
end
function main()
config.load()
remote_build_client.singleton():runcmd("xmake", xmake.argv())
end
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.