All files / src/rules xml_consistency.ts

98.83% Statements 338/342
76.25% Branches 122/160
100% Functions 22/22
98.83% Lines 338/342

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 3431x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 29465x 29465x 29465x 29465x 29465x 29465x 29465x 29465x 1x 14782x 14782x 14782x 14782x 14782x 72231x 72231x 72231x 72231x 72231x 72231x 72231x 72231x 72231x 72231x 72231x 72231x 72231x 72231x 72231x 14782x 14782x 14120x 14120x 14782x 14782x 268x 268x 14782x 14782x 365x 365x 14782x 14782x 462x 462x 462x 462x 262x 262x 200x 200x 200x 200x 200x 10x 200x 190x 380x 380x 2x 2x 380x 190x 200x 200x 200x 462x 17x 462x 5x 183x 48x 178x 10x 130x 6x 120x 10x 114x 59x 104x 5x 5x 200x 462x 50x 50x 200x 200x 200x 14782x 14782x 17x 17x 17x   17x 1x 17x 1x 16x 1x 1x 17x 17x 14782x 14782x 50x 50x 50x 10x 10x 50x 4x 4x 4x 4x 50x 50x 14782x 14782x 5x 5x 5x   5x   5x   5x 1x 1x 5x 5x 14782x 14782x 318x 318x 114x 114x 318x 318x 34x 34x 34x 34x 34x 170x 170x 14782x 14782x 48x 48x 48x 48x 48x 48x 48x 48x 48x 32x 32x 32x 48x 27x 27x 27x 48x 27x 27x 27x 48x 27x 27x 27x 48x 35x 35x 35x 48x 48x 48x 48x 48x 48x 48x 48x 240x 240x 48x 48x 5x 5x 5x 5x 5x 5x 5x 5x 25x 25x 5x 48x 48x 48x 14782x 14782x 148x 14x 14x 14x 134x 134x 14782x 14782x 10x 10x 10x 10x 10x 10x 10x 10x 4x 4x 10x 3x 3x 10x 10x 10x 14782x 14782x 6x 6x 6x 6x 6x 6x 6x 6x 4x 4x 6x 6x 6x 14782x 14782x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 2x 2x 10x 10x 10x 14782x 14782x 5x 5x 5x 7x 3x 3x 3x 3x 7x 5x 5x 14782x 14782x 14782x 14782x 14782x 14782x 14782x 14782x 14782x 14782x 14782x 14782x 59x 59x 108x 1x 1x 1x 108x 108x 108x 3x 3x 3x 3x 108x 59x 59x 36x 36x 36x 36x 61x 7x 7x 7x 61x 36x 3x 3x 3x 36x 3x 3x 3x 36x 59x 59x 59x 14782x  
import {Issue} from "../issue";
import {IRule, IRuleMetadata, RuleTag} from "./_irule";
import {IObject} from "../objects/_iobject";
import {IFile} from "../files/_ifile";
import * as Objects from "../objects";
import {ABAPObject} from "../objects/_abap_object";
import {IRegistry} from "../_iregistry";
import {BasicRuleConfig} from "./_basic_rule_config";
import {XMLValidator} from "fast-xml-parser";
import {Severity} from "../severity";
 
const ABAPGIT_ATTRIBUTES: [string, RegExp][] = [
  ["version", /<abapGit\b[^>]*\bversion="([^"]+)"/],
  ["serializer_version", /<abapGit\b[^>]*\bserializer_version="([^"]+)"/],
];
 
export class XMLConsistencyConf extends BasicRuleConfig {
  /** Problem severity for text and translation length checks */
  public textAndTranslationLengthSeverity?: Severity = Severity.Error;
  /** Problem severity for data element(DTEL) field checks */
  public dataElementSeverity?: Severity = Severity.Error;
  /** Problem severity for transparent table checks */
  public transparentTableSeverity?: Severity = Severity.Error;
}
 
export class XMLConsistency implements IRule {
 
  private conf = new XMLConsistencyConf();
 
  public getMetadata(): IRuleMetadata {
    return {
      key: "xml_consistency",
      title: "XML consistency",
      shortDescription: `Checks the consistency of main XML files`,
      extendedInformation: `Checks:
* XML is well-formed and parseable
* Naming for CLAS and INTF objects
* QUAN fields in TABL objects have reference table and field values
* Transparent TABL objects have delivery class and size category set
* TABL fields with a built-in type carry the INTTYPE abapGit serializes for it, for the confirmed pairs
* Lock parameter names in ENQU objects are max 16 characters
* Texts and translations do not exceed maximum allowed length.`,
      tags: [RuleTag.Naming, RuleTag.Syntax],
    };
  }
 
  public getConfig() {
    return this.conf;
  }
 
  public setConfig(conf: XMLConsistencyConf) {
    this.conf = conf;
  }
 
  public initialize(_reg: IRegistry) {
    return this;
  }
 
  public run(obj: IObject): Issue[] {
    const issues: Issue[] = [];
 
    const file = obj.getXMLFile();
    if (file === undefined) {
      return issues;
    }
 
    const xml = obj.getXML();
    if (xml) {
      const res = XMLValidator.validate(xml);
      if (res !== true) {
        issues.push(Issue.atRow(file, 1, "XML parser error: " + res.err.msg, this.getMetadata().key, this.conf.severity));
      } else {
        for (const [attribute, regex] of ABAPGIT_ATTRIBUTES) {
          const value = xml.match(regex)?.[1];
          if (value !== undefined && value.match(/^v\d\.\d\.\d$/) === null) {
            issues.push(Issue.atRow(file, 1, `Unexpected abapGit ${attribute} "${value}"`, this.getMetadata().key, this.conf.severity));
          }
        }
      }
    }
 
    // todo, have some XML validation in each object?
    if (obj instanceof Objects.Class) {
      issues.push(...this.runClass(obj, file));
    } else if (obj instanceof Objects.Interface) {
      issues.push(...this.runInterface(obj, file));
    } else if (obj instanceof Objects.DataElement) {
      issues.push(...this.runDataElement(obj, file));
    } else if (obj instanceof Objects.Domain) {
      issues.push(...this.runDomain(obj, file));
    } else if (obj instanceof Objects.Transaction) {
      issues.push(...this.runTransaction(obj, file));
    } else if (obj instanceof Objects.MessageClass) {
      issues.push(...this.runMessageClass(obj, file));
    } else if (obj instanceof Objects.Table) {
      issues.push(...this.runTable(obj, file));
    } else if (obj instanceof Objects.LockObject) {
      issues.push(...this.runLockObject(obj, file));
    }
 
    if (obj instanceof ABAPObject) {
      issues.push(...this.runTextPool(obj, file));
    }
 
    return issues;
  }
 
  private runClass(obj: Objects.Class, file: IFile): Issue[] {
    const issues: Issue[] = [];
    const name = obj.getNameFromXML();
    if (name === undefined) {
      issues.push(Issue.atRow(file, 1, "Name undefined in XML", this.getMetadata().key, this.conf.severity));
    } else if (obj.getDescription() && obj.getDescription()!.length > 60) {
      issues.push(Issue.atRow(file, 1, "Description too long", this.getMetadata().key, this.conf.severity));
    } else if (name !== obj.getName().toUpperCase()) {
      issues.push(Issue.atRow(file, 1, "Name in XML does not match object", this.getMetadata().key, this.conf.severity));
    } else if (obj.getMainABAPFile()?.getStructure() !== undefined && obj.getClassDefinition() === undefined) {
      issues.push(Issue.atRow(file, 1, "Class matching XML name not found in ABAP file", this.getMetadata().key, this.conf.severity));
    }
    return issues;
  }
 
  private runTextPool(obj: ABAPObject, file: IFile): Issue[] {
    const issues: Issue[] = [];
    const push = (issue: Issue | undefined) => { if (issue) { issues.push(issue); } };
    for (const [key, el] of Object.entries(obj.getTextElements())) {
      push(this.checkTextLength(file, `ENTRY[${key}]`, el.entry, el.maxLength));
    }
    for (const translation of obj.getTextElementsTranslations()) {
      for (const [key, el] of Object.entries(translation.textElements)) {
        push(this.checkTextLength(file, `ENTRY[${key}]`, el.entry, el.maxLength, translation.language));
      }
    }
    return issues;
  }
 
  private runInterface(obj: Objects.Interface, file: IFile): Issue[] {
    const issues: Issue[] = [];
    const name = obj.getNameFromXML();
    if (name === undefined) {
      issues.push(Issue.atRow(file, 1, "Name undefined in XML", this.getMetadata().key, this.conf.severity));
    } else if (obj.getDescription() && obj.getDescription()!.length > 60) {
      issues.push(Issue.atRow(file, 1, "Description too long", this.getMetadata().key, this.conf.severity));
    } else if (name !== obj.getName().toUpperCase()) {
      issues.push(Issue.atRow(file, 1, "Name in XML does not match object", this.getMetadata().key, this.conf.severity));
    } else if (obj.getDefinition() !== undefined && obj.getDefinition()?.getName().toUpperCase() !== name.toUpperCase()) {
      issues.push(Issue.atRow(file, 1, "Interface matching XML name not found in ABAP file", this.getMetadata().key, this.conf.severity));
    }
    return issues;
  }
 
  private checkTextLength(file: IFile, fieldName: string, text: string | undefined,
                          maxLength: string | number | undefined, lang?: string): Issue | undefined {
    if (text === undefined || maxLength === undefined) {
      return undefined;
    }
    const max = typeof maxLength === "number" ? maxLength : parseInt(maxLength, 10);
    if (text.length > max) {
      const prefix = lang ? `[${lang}] ` : "";
      return Issue.atRow(file, 1,
                         `${prefix}${fieldName} "${text}" exceeds maximum length of ${max} characters (actual: ${text.length})`,
                         this.getMetadata().key, this.conf.textAndTranslationLengthSeverity);
    }
    return undefined;
  }
 
  private runDataElement(obj: Objects.DataElement, file: IFile): Issue[] {
    const issues: Issue[] = [];
    const texts = obj.getTexts();
    const maxLengths = obj.getTextMaxLengths();
    const hasLabelTexts = texts?.short !== undefined
      || texts?.medium !== undefined
      || texts?.long !== undefined
      || texts?.heading !== undefined;
 
    if (texts?.short !== undefined) {
      const issue = this.checkRequiredField(file, "SCRLEN1", maxLengths?.short);
      if (issue) {issues.push(issue);}
    }
    if (texts?.medium !== undefined) {
      const issue = this.checkRequiredField(file, "SCRLEN2", maxLengths?.medium);
      if (issue) {issues.push(issue);}
    }
    if (texts?.long !== undefined) {
      const issue = this.checkRequiredField(file, "SCRLEN3", maxLengths?.long);
      if (issue) {issues.push(issue);}
    }
    if (texts?.heading !== undefined) {
      const issue = this.checkRequiredField(file, "HEADLEN", maxLengths?.heading);
      if (issue) {issues.push(issue);}
    }
    if (hasLabelTexts) {
      const issue = this.checkRequiredField(file, "DTELMASTER", obj.getDtelMaster());
      if (issue) {issues.push(issue);}
    }
 
    for (const issue of [
      this.checkTextLength(file, "DDTEXT", obj.getDescription(), 60),
      this.checkTextLength(file, "SCRTEXT_S", texts?.short, maxLengths?.short),
      this.checkTextLength(file, "SCRTEXT_M", texts?.medium, maxLengths?.medium),
      this.checkTextLength(file, "SCRTEXT_L", texts?.long, maxLengths?.long),
      this.checkTextLength(file, "REPTEXT", texts?.heading, maxLengths?.heading),
    ]) {
      if (issue) {issues.push(issue);}
    }
 
    for (const translation of obj.getTextsTranslations() ?? []) {
      const lang = translation.language;
      for (const issue of [
        this.checkTextLength(file, "DDTEXT", translation.description, 60, lang),
        this.checkTextLength(file, "SCRTEXT_S", translation.short, maxLengths?.short, lang),
        this.checkTextLength(file, "SCRTEXT_M", translation.medium, maxLengths?.medium, lang),
        this.checkTextLength(file, "SCRTEXT_L", translation.long, maxLengths?.long, lang),
        this.checkTextLength(file, "REPTEXT", translation.heading, maxLengths?.heading, lang),
      ]) {
        if (issue) {issues.push(issue);}
      }
    }
 
    return issues;
  }
 
  private checkRequiredField(file: IFile, fieldName: string, value: string | undefined): Issue | undefined {
    if (value === undefined || value === "") {
      return Issue.atRow(file, 1, `Missing required field ${fieldName} in DD04V`,
                         this.getMetadata().key, this.conf.dataElementSeverity);
    }
    return undefined;
  }
 
  private runDomain(obj: Objects.Domain, file: IFile): Issue[] {
    const maxTextLength = 60;
    const issues: Issue[] = [];
 
    const push = (issue: Issue | undefined) => { if (issue) { issues.push(issue); } };
 
    push(this.checkTextLength(file, "DDTEXT", obj.getDescription(), maxTextLength));
 
    for (const fixedValue of obj.getFixedValues() ?? []) {
      push(this.checkTextLength(file, "DDTEXT", fixedValue.description, maxTextLength, fixedValue.language));
    }
    for (const translationFixedValue of obj.getFixedValuesTranslations() ?? []) {
      push(this.checkTextLength(file, "DDTEXT", translationFixedValue.description, maxTextLength, translationFixedValue.language));
    }
 
    return issues;
  }
 
  private runTransaction(obj: Objects.Transaction, file: IFile): Issue[] {
    const maxTextLength = 36;
    const issues: Issue[] = [];
 
    const push = (issue: Issue | undefined) => { if (issue) { issues.push(issue); } };
 
    push(this.checkTextLength(file, "TTEXT", obj.getDescription(), maxTextLength));
 
    for (const translation of obj.getTextsTranslations() ?? []) {
      push(this.checkTextLength(file, "TTEXT", translation.description, maxTextLength, translation.language));
    }
 
    return issues;
  }
 
  private runMessageClass(obj: Objects.MessageClass, file: IFile): Issue[] {
    const maxTextLength = 73;
    const issues: Issue[] = [];
 
    const push = (issue: Issue | undefined) => { if (issue) { issues.push(issue); } };
 
    for (const msg of obj.getMessages()) {
      push(this.checkTextLength(file, `TEXT[${msg.getNumber()}]`, msg.getMessage(), maxTextLength));
    }
 
    for (const translation of obj.getTextsTranslations() ?? []) {
      push(this.checkTextLength(file, `TEXT[${translation.number}]`, translation.text, maxTextLength, translation.language));
    }
 
    return issues;
  }
 
  private runLockObject(obj: Objects.LockObject, file: IFile): Issue[] {
    const maxParameterLength = 16;
    const issues: Issue[] = [];
    for (const parameter of obj.getParameters() ?? []) {
      if (parameter.VIEWFIELD.length > maxParameterLength) {
        const message = `Lock parameter ${parameter.VIEWFIELD} exceeds maximum length of ` +
          `${maxParameterLength} characters (actual: ${parameter.VIEWFIELD.length})`;
        issues.push(Issue.atRow(file, 1, message, this.getMetadata().key, this.conf.severity));
      }
    }
    return issues;
  }
 
  // INTTYPE that abapGit serializes for a built-in DATATYPE, confirmed by exported tables;
  // a different value activates, but shows as a diff on every pull
  private static readonly intTypes: {[datatype: string]: string} = {
    "CHAR": "C", "CLNT": "C", "CUKY": "C", "LANG": "C",
    "DATS": "D", "TIMS": "T",
    "INT4": "X", "RAW": "X",
    "DEC": "P", "CURR": "P",
    "STRG": "g", "SSTR": "g", "RSTR": "y",
  };
 
  private runTable(obj: Objects.Table, file: IFile): Issue[] {
    const issues: Issue[] = [];
    for (const field of obj.getFields() ?? []) {
      if (field.DATATYPE === "QUAN" && (!field.REFTABLE?.trim() || !field.REFFIELD?.trim())) {
        const message = `QUAN field ${field.FIELDNAME} must have REFTABLE and REFFIELD set`;
        issues.push(Issue.atRow(file, 1, message, this.getMetadata().key, this.conf.severity));
      }
 
      const expected = field.DATATYPE ? XMLConsistency.intTypes[field.DATATYPE] : undefined;
      if (expected !== undefined && field.INTTYPE !== undefined && field.INTTYPE !== expected) {
        const message = `Field ${field.FIELDNAME}: INTTYPE "${field.INTTYPE}" does not match DATATYPE ${field.DATATYPE}, ` +
          `abapGit serializes "${expected}"`;
        issues.push(Issue.atRow(file, 1, message, this.getMetadata().key, this.conf.severity));
      }
    }
 
    if (obj.getTableCategory() === Objects.TableCategory.Transparent) {
      // Confirmed reserved database field names, see issue #4331, DAY and HOUR reported by activation.
      // TRESE also contains names such as TEXT and LENGTH which are allowed here.
      const reservedFieldNames = ["ZONE", "HANDLER", "SECTION", "PARAMETER", "DAY", "HOUR"];
      for (const field of obj.getFields() ?? []) {
        if (reservedFieldNames.includes(field.FIELDNAME.toUpperCase())) {
          issues.push(Issue.atRow(file, 1, `Table field name "${field.FIELDNAME}" is reserved`,
                                  this.getMetadata().key, this.conf.severity));
        }
      }
      if (!obj.getDeliveryClass()?.trim()) {
        const message = `Transparent table must have delivery class(CONTFLAG in DD02V) set`;
        issues.push(Issue.atRow(file, 1, message, this.getMetadata().key, this.conf.transparentTableSeverity));
      }
      if (!obj.getSizeCategory()?.trim()) {
        const message = `Transparent table must have size category(TABKAT in DD09L) set`;
        issues.push(Issue.atRow(file, 1, message, this.getMetadata().key, this.conf.transparentTableSeverity));
      }
    }
 
    return issues;
  }
}