Skip to content

Commit

Permalink
Merge remote-tracking branch 'origin/fix/umijs_proxy' into fix/umijs_…
Browse files Browse the repository at this point in the history
…proxy
  • Loading branch information
huanyu.why committed Sep 13, 2024
2 parents e66dbfe + 53427ac commit dd9b152
Show file tree
Hide file tree
Showing 7 changed files with 164 additions and 28 deletions.
12 changes: 7 additions & 5 deletions crates/mako/src/generate/chunk_pot/str_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,12 +112,14 @@ pub(super) fn render_normal_js_chunk(
) -> Result<ChunkFile> {
let (content_buf, source_map_buf) = {
let pot = chunk_pot;

// to avoid ' or " been included in chunk_loading_global
let safe_prop = serde_json::to_string(&context.config.output.chunk_loading_global).unwrap();

Check warning on line 117 in crates/mako/src/generate/chunk_pot/str_impl.rs

View check run for this annotation

Codecov / codecov/patch

crates/mako/src/generate/chunk_pot/str_impl.rs#L117

Added line #L117 was not covered by tests

let chunk_prefix_code = format!(
r#"((typeof globalThis !== 'undefined' ? globalThis : self)['{}'] = (typeof globalThis !== 'undefined' ? globalThis : self)['{}'] || []).push([
['{}'],"#,
context.config.output.chunk_loading_global,
context.config.output.chunk_loading_global,
pot.chunk_id,
r#"((typeof globalThis !== 'undefined' ? globalThis : self)[{}] = (typeof globalThis !== 'undefined' ? globalThis : self)[{}] || []).push([
['{}'],"#,
safe_prop, safe_prop, pot.chunk_id,
);

let (chunk_content, chunk_raw_sourcemap) = pot_to_chunk_module_object_string(
Expand Down
1 change: 1 addition & 0 deletions e2e/fixtures.umi/dev.hmr/app.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
import "./global.css"
Original file line number Diff line number Diff line change
Expand Up @@ -2,36 +2,38 @@ import assert from "assert";
import 'zx/globals';

const port = '8000';

async function fetchHome() {
const res = await fetch(`http://localhost:${port}`);
assert(res.status === 200, "should start umi dev server");
assert(res.headers.get("content-type").includes("text/html"), "should return html");
return res;
}

async function fetchApi(){
async function fetchApi() {
const res = await fetch(`http://localhost:${port}/api/users`);
assert(res.status === 200, "should return 200");
assert(res.headers.get("content-type").includes("application/json"), "should return json");
return res;
}

async function fetchHTMLFile(){
async function fetchHTMLFile() {
const res = await fetch(`http://localhost:${port}/test.html`);
assert(res.status === 200, "should return 200");
assert(res.headers.get("content-type").includes("text/html"), "should return html");
return res;
}

async function fetchCSSFile(){
async function fetchCSSFile() {
const res = await fetch(`http://localhost:${port}/umi.css`);
assert(res.status === 200, "should return 200");
assert(res.headers.get("content-type").includes("text/css"), "should return css");
return res;
}

await fetchHome();
await fetchApi();
await fetchHTMLFile();
await fetchCSSFile();
$`lsof -i :${port} -t | xargs kill -9`
export default async function () {
await fetchHome();
await fetchApi();
await fetchHTMLFile();
await fetchCSSFile();
}
3 changes: 3 additions & 0 deletions e2e/fixtures.umi/dev.hmr/global.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
body {
color: red;
}
32 changes: 17 additions & 15 deletions scripts/test-e2e.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -62,18 +62,11 @@ const dirs = fs.readdirSync(fixtures).filter((dir) => {
);
});
// import expect.mjs or expect.js
async function runExpect(dir) {
const expectPath = [
`file://${path.join(fixtures, dir, 'expect.js')}`,
`file://${path.join(fixtures, dir, 'expect.mjs')}`,
];
const mod = await Promise.any(
expectPath.map(async (path) => {
return import(path);
}),
);
async function runExpect(dir, error) {
const expectPath = `file://${path.join(fixtures, dir, 'expect.js')}`;
const mod = await import(expectPath);
if (mod && typeof mod.default === 'function') {
await mod.default();
await mod.default(error);
}
}
for (const dir of onlyDir ? [onlyDir] : dirs) {
Expand All @@ -92,16 +85,25 @@ for (const dir of onlyDir ? [onlyDir] : dirs) {
// 如果目录名以dev开头,则运行dev命令否则运行build命令
if (dir.startsWith('dev')) {
console.log(`cd ${cwd} && umi dev`);
$.spawn('sh', ['-c', `cd ${cwd} && umi dev`], { stdio: 'inherit' });
let p = $.spawn('sh', ['-c', `cd ${cwd} && OKAM=${x} umi dev`], {
stdio: 'inherit',
});
const isRunning = await waitForServer(
defaultPort,
defaultPort + 1, // mako's port, when it's open, dev can serve
'localhost',
1000,
30,
);
if (isRunning) {
console.log(`Server is running on port ${defaultPort}`);
await runExpect(dir);
try {
await runExpect(dir);
} catch (e) {
console.log('dev error', e);
throw e;
} finally {
p.kill(9);
}
} else {
console.log(`Failed to connect to server on port ${defaultPort}`);
}
Expand All @@ -117,7 +119,7 @@ for (const dir of onlyDir ? [onlyDir] : dirs) {
} catch (e) {
const isErrorCase = dir.split('.').includes('error');
if (isErrorCase) {
await runExpect(dir);
await runExpect(dir, e);
return;
} else {
throw e;
Expand Down
84 changes: 84 additions & 0 deletions scripts/tools/sub-cli.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
#!/usr/bin/env python3

import networkx as nx
from networkx.drawing.nx_agraph import write_dot, read_dot
import argparse
import subprocess

def find_reachable_nodes_and_subgraph(dot_file, target_nodes, n, output_dot_file):
# 读取 .dot 文件,创建图对象
G = read_dot(dot_file)

# BFS 搜索,找到 n 跳内的所有节点
reachable_nodes = set()
edges = set()

# BFS 队列初始化
queue = [(node, 0) for node in target_nodes]

while queue:
current_node, current_depth = queue.pop(0)

if current_depth > n:
continue

reachable_nodes.add(current_node)

# 遍历当前节点的前驱节点
for predecessor in G.predecessors(current_node):
queue.append((predecessor, current_depth + 1))
edges.add((predecessor, current_node))

# 构建子图
subgraph = G.subgraph(reachable_nodes).copy()

# 将子图保存为 .dot 文件
write_dot(subgraph, output_dot_file)
print(f"Subgraph with reachable nodes saved to {output_dot_file}")

def select_target_nodes(G):
# 创建一个 {label: node_id} 的映射
label_to_node = {}

for node in G.nodes(data=True):
node_id = node[0]
node_label = node[1].get('label', node_id) # 如果没有 label,使用节点 ID
label_to_node[node_label] = node_id

# 使用 fzf 选择节点 label,允许多选
process = subprocess.Popen(
['fzf', '--multi'], stdin=subprocess.PIPE, stdout=subprocess.PIPE
)
fzf_input = "\n".join(label_to_node.keys()).encode('utf-8')
stdout, _ = process.communicate(input=fzf_input)

# 解析选择的节点,fzf 返回多个节点的 label 时是用换行符分隔的
selected_labels = stdout.decode('utf-8').strip().split('\n')

# 将选中的 labels 映射为节点 ID
selected_nodes = [label_to_node[label] for label in selected_labels if label in label_to_node]

return selected_nodes

def main():
# 设置命令行参数
parser = argparse.ArgumentParser(description='从 Graphviz .dot 文件中生成子图')
parser.add_argument('dot_file', type=str, help='输入的 .dot 文件路径')
parser.add_argument('-n', '--hops', type=int, default=3, help='最大跳数')
parser.add_argument('-o', '--output', type=str, default='subgraph_output.dot', help='输出的子图 .dot 文件')

# 解析命令行参数
args = parser.parse_args()

# 读取图
G = read_dot(args.dot_file)

# 使用 fzf 选择目标节点
target_nodes = select_target_nodes(G)

# 执行子图查找
if target_nodes:
find_reachable_nodes_and_subgraph(args.dot_file, target_nodes, args.hops, args.output)

if __name__ == '__main__':
main()
42 changes: 42 additions & 0 deletions scripts/tools/sub-cli.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
## prerequiere

```bash
pip install networkx
pip install pygraphviz
```
if install `pygraphviz` failed, you can try to install `graphviz` first then

```bash
CFLAGS='-I/opt/homebrew/include/' LDFLAGS='-L/opt/homebrew/lib' pip install pygraphviz
```


## how to use

```txt
subdot -h
usage: subdot [-h] [-n HOPS] [-o OUTPUT] dot_file

从 Graphviz .dot 文件中生成子图

positional arguments:
dot_file 输入的 .dot 文件路径

options:
-h, --help show this help message and exit
-n HOPS, --hops HOPS 最大跳数
-o OUTPUT, --output OUTPUT
输出的子图 .dot 文件
```

First, `DEBUG_GRAPH=true npm run build` to generate `_mako_*.dot` files in the root of project.

Then, run the following command

```bash
python sub-cli.py _mako_chunk_graph_origin.dot
```

select the nodes in fzf TUI (multi mode is on ,`Tab` to select, `Shift Tab` to un-select).

it will generate `subgraph_output.dot`, then debug this dot file.

0 comments on commit dd9b152

Please sign in to comment.