任务
扫描指令序列,定位依赖安装指令,若在其之前出现整树复制的 COPY,则判定缓存不安全并给出建议顺序。
契约
- 输入:JSON 对象:{ instructions: [{ cmd, args }] }
- 输出:JSON 对象:{ cacheSafe: boolean, offending: number[], suggestion: string }
样例
- 输入
{"instructions":[{"cmd":"FROM","args":"node:22"},{"cmd":"COPY","args":"package*.json ./"},{"cmd":"RUN","args":"npm ci"},{"cmd":"COPY","args":". ."}]}-> 期望{"cacheSafe":true,"offending":[],"suggestion":"layer order keeps dependency cache intact"}。依赖先装、源码后复制,因此安装层能在代码改动后继续命中缓存。 - 输入
{"instructions":[{"cmd":"FROM","args":"node:22"},{"cmd":"COPY","args":". ."},{"cmd":"RUN","args":"npm ci"}]}-> 期望{"cacheSafe":false,"offending":[1],"suggestion":"move COPY of sources after the dependency install layer"}。先复制源码意味着任何文件变更都会使安装层失效。
参考实现
function solve({ instructions }) {
const installIdx = instructions.findIndex(
(ins) => ins.cmd === 'RUN' && /(npm ci|npm install|pip install|go mod download)/.test(ins.args),
);
const offending = [];
instructions.forEach((ins, index) => {
if (installIdx !== -1 && index < installIdx && ins.cmd === 'COPY' && /^\.\s*\.$/.test(ins.args.trim())) {
offending.push(index);
}
});
return {
cacheSafe: offending.length === 0,
offending,
suggestion: offending.length
? 'move COPY of sources after the dependency install layer'
: 'layer order keeps dependency cache intact',
};
}
为什么有效
层顺序决定重建时间。在安装依赖之前复制整棵源码树,会让改一行注释都触发重新安装。
只有安装步骤之前的整树 COPY(“.” “.”)会破坏缓存;先复制清单文件是正确做法。