Inno Setup - 如果尚不存在,则在特定行之前向文本 file/template 插入一行

Inno Setup - Insert a line to a text file/template before a specific line if doesn't exist yet

如果 file/template 不存在,如何在特定的其他行之前添加一行?

例如,对于以下 JS 文件,我必须确保 ABOVE THIS LINEBELOW THIS LINE 注释行之间有 dependencies.push(...) 行。如果 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 模板文件做同样的事情。

感谢您的帮助。

您必须逐行解析文件以找到插入代码的位置。

像这样:

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 writing %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 文件时,请注意 LoadStringsFromFileSaveStringsToFile 限制。参见