setapi: error out when file is not on editions yet

PiperOrigin-RevId: 707516588
Change-Id: Iac61f5a87c6f46fa309240efaf36c5ebc461727a
Reviewed-on: https://go-review.googlesource.com/c/open2opaque/+/637375
Reviewed-by: Michael Stapelberg <stapelberg@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Michael Stapelberg <stapelberg@google.com>
Reviewed-by: Chressie Himpel <chressie@google.com>
diff --git a/internal/o2o/setapi/setapi.go b/internal/o2o/setapi/setapi.go
index 32d48d9..4a9acdf 100644
--- a/internal/o2o/setapi/setapi.go
+++ b/internal/o2o/setapi/setapi.go
@@ -393,6 +393,13 @@
 	return slices.Insert(in, beginByte, insert...), nil
 }
 
+func levelLineFor(fopt *protoparse.FileOpt, targetAPI gofeaturespb.GoFeatures_APILevel) (string, error) {
+	if fopt.Syntax == "editions" {
+		return fmt.Sprintf("option features.(pb.go).api_level = %s;", targetAPI), nil
+	}
+	return "", fmt.Errorf("file %s is not using Protobuf Editions (https://protobuf.dev/editions/overview/) yet", fopt.File)
+}
+
 func setFileAPI(path string, content []byte, targetAPI gofeaturespb.GoFeatures_APILevel, skipCleanup, errorOnExempt bool) ([]byte, error) {
 	fopt, err := parse(path, content, true)
 	if err != nil {
@@ -426,6 +433,11 @@
 		return slices.Delete(content, from, to), nil
 	}
 
+	levelLine, err := levelLineFor(fopt, targetAPI)
+	if err != nil {
+		return nil, err
+	}
+
 	if !fopt.IsExplicit {
 		logf("Inserting API flag %q into file %s", targetAPI, path)
 
@@ -433,10 +445,6 @@
 		if err != nil {
 			return nil, fmt.Errorf("fileOptionLineNumber: %v", err)
 		}
-		levelLine := fmt.Sprintf("option go_api_flag = %q;", fromFeatureToOld(targetAPI))
-		if fopt.Syntax == "editions" {
-			levelLine = fmt.Sprintf("option features.(pb.go).api_level = %s;", targetAPI)
-		}
 		return insertLine(content, levelLine, ln), nil
 	}
 
@@ -454,11 +462,7 @@
 		return content, nil
 	}
 	logf("Replacing the API flag of file %s", path)
-	insert := fmt.Sprintf("option go_api_flag = %q;", fromFeatureToOld(targetAPI))
-	if fopt.Syntax == "editions" {
-		insert = fmt.Sprintf("option features.(pb.go).api_level = %s;", targetAPI)
-	}
-	content, err = replaceTextRange(content, fopt.APIInfo.TextRange, []byte(insert))
+	content, err = replaceTextRange(content, fopt.APIInfo.TextRange, []byte(levelLine))
 	if err != nil {
 		return nil, fmt.Errorf("replaceTextRange: %v", err)
 	}