如果不存在特定的其他行,如何在文件/模板中添加一行?
例如,对于以下JS文件,我必须确保dependencies.push(...)
和ABOVE THIS LINE
注释行之间有BELOW THIS LINE
行。如果dependencies.push(...)
不存在,我必须在BELOW THIS LINE
评论行之前添加:
(function(ng) {
var dependencies = [];
/*DO NOT MODIFY ABOVE THIS LINE!*/
dependencies.push("mxdfNewTransaction.controller.mxdfNewTransactionCtrl");
/*DO NOT MODIFY BELOW THIS LINE!*/
ng.module('prismApp.customizations', dependencies, null);
})(angular);
我还必须使用类似的HTML模板文件执行相同的操作。
感谢您的帮助。
答案 0 :(得分:1)
您必须逐行解析文件以找到插入代码的位置。
这样的事情:
function AddLineToTemplate(
FileName: string; StartLine, EndLine, AddLine: string): Boolean;
var
Lines: TArrayOfString;
Count, I, I2: Integer;
Line: string;
State: Integer;
begin
Result := True;
if not LoadStringsFromFile(FileName, Lines) then
begin
Log(Format('Error reading %s', [FileName]));
Result := False;
end
else
begin
State := 0;
Count := GetArrayLength(Lines);
for I := 0 to Count - 1 do
begin
Line := Trim(Lines[I]);
if (CompareText(Line, StartLine) = 0) then
begin
State := 1;
Log(Format('Start line found at %d', [I]));
end
else
if (State = 1) and (CompareText(Line, AddLine) = 0) then
begin
Log(Format('Line already present at %d', [I]));
State := 2;
break;
end
else
if (State = 1) and (CompareText(Line, EndLine) = 0) then
begin
Log(Format('End line found at %d, inserting', [I]));
SetArrayLength(Lines, Count + 1);
for I2 := Count - 1 downto I do
Lines[I2 + 1] := Lines[I2];
Lines[I] := AddLine;
State := 2;
if not SaveStringsToFile(FileName, Lines, False) then
begin
Log(Format('Error writting %s', [FileName]));
Result := False;
end
else
begin
Log(Format('Modifications saved to %s', [FileName]));
end;
break;
end;
end;
if Result and (State <> 2) then
begin
Log(Format('Spot to insert line was not found in %s', [FileName]));
Result := False;
end;
end;
end;
你可以像这样使用它:
if AddLineToTemplate(
'C:\path\to\customizations.js',
'/*DO NOT MODIFY ABOVE THIS LINE!*/',
'/*DO NOT MODIFY BELOW THIS LINE!*/',
' dependencies.push("mxdfNewTransaction.controller.mxdfNewTransactionCtrl");') then
begin
Log('Success');
end
else
begin
Log('Failure');
end;
在使用Unicode文件时,请注意LoadStringsFromFile
和SaveStringsToFile
限制。请参阅Inno Setup Reading file in Ansi and Unicode encoding。