getParentFile static method

Either get the referenced parent file, or try to infer which it might be.

Implementation

static MessagesWithMetadata getParentFile(
  List<MessagesWithMetadata> arbResources,
  MessagesWithMetadata arb,
) {
  /// If the reference file is explicitly named, return that.
  if (arb.referencePath != null) {
    final reference = arbResources
        .where((element) => element.assetId.path == arb.referencePath)
        .firstOrNull;
    if (reference != null) {
      return reference;
    }
  }

  /// If the current file is a reference for others, return the current file.
  final references = arbResources
      .where((resource) => resource.referencePath == arb.assetId.path);
  if (references.contains(arb)) {
    return arb;
  }

  /// Try to infer by looking at which files contain metadata, which is a sign
  /// they might be the references for others in the same context.
  final contextLeads =
      arbResources.groupListsBy((resource) => resource.context);
  final contextWithMetadata = contextLeads[arb.context]!
      .firstWhereOrNull((element) => element.hasMetadata);
  if (contextWithMetadata != null) {
    return contextWithMetadata;
  }

  return arb;
}