| 1 |
/* |
| 2 |
* Copyright (C) 2014 The Android Open Source Project |
| 3 |
* |
| 4 |
* Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 |
* you may not use this file except in compliance with the License. |
| 6 |
* You may obtain a copy of the License at |
| 7 |
* |
| 8 |
* http://www.apache.org/licenses/LICENSE-2.0 |
| 9 |
* |
| 10 |
* Unless required by applicable law or agreed to in writing, software |
| 11 |
* distributed under the License is distributed on an "AS IS" BASIS, |
| 12 |
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 |
* See the License for the specific language governing permissions and |
| 14 |
* limitations under the License. |
| 15 |
*/ |
| 16 |
|
| 17 |
package com.android.manifmerger; |
| 18 |
|
| 19 |
import com.android.SdkConstants; |
| 20 |
import com.android.annotations.NonNull; |
| 21 |
import com.android.annotations.Nullable; |
| 22 |
import com.android.ide.common.blame.SourceFile; |
| 23 |
import com.android.ide.common.blame.SourcePosition; |
| 24 |
import com.android.ide.common.res2.MergingException; |
| 25 |
import com.android.utils.ILogger; |
| 26 |
import com.android.utils.SdkUtils; |
| 27 |
import com.android.utils.XmlUtils; |
| 28 |
import com.google.common.base.Joiner; |
| 29 |
import com.google.common.base.Objects; |
| 30 |
import com.google.common.base.Optional; |
| 31 |
import com.google.common.base.Preconditions; |
| 32 |
import com.google.common.base.Splitter; |
| 33 |
import com.google.common.collect.ImmutableList; |
| 34 |
import com.google.common.collect.ImmutableMap; |
| 35 |
import com.google.common.collect.Lists; |
| 36 |
|
| 37 |
import org.w3c.dom.Attr; |
| 38 |
import org.w3c.dom.Element; |
| 39 |
import org.w3c.dom.NamedNodeMap; |
| 40 |
import org.w3c.dom.Node; |
| 41 |
import org.w3c.dom.NodeList; |
| 42 |
import org.w3c.dom.Text; |
| 43 |
|
| 44 |
import java.util.ArrayList; |
| 45 |
import java.util.Collection; |
| 46 |
import java.util.List; |
| 47 |
import java.util.Map; |
| 48 |
|
| 49 |
/** |
| 50 |
* Xml {@link org.w3c.dom.Element} which is mergeable. |
| 51 |
* |
| 52 |
* A mergeable element can contains 3 types of children : |
| 53 |
* <ul> |
| 54 |
* <li>a child element, which itself may or may not be mergeable.</li> |
| 55 |
* <li>xml attributes which are related to the element.</li> |
| 56 |
* <li>tools oriented attributes to trigger specific behaviors from the merging tool</li> |
| 57 |
* </ul> |
| 58 |
* |
| 59 |
* The two main responsibilities of this class is to be capable of comparing itself against |
| 60 |
* another instance of the same type as well as providing XML element merging capabilities. |
| 61 |
*/ |
| 62 |
public class XmlElement extends OrphanXmlElement { |
| 63 |
|
| 64 |
@NonNull |
| 65 |
private final XmlDocument mDocument; |
| 66 |
|
| 67 |
@Nullable |
| 68 |
private final NodeOperationType mNodeOperationType; |
| 69 |
|
| 70 |
// list of non tools related attributes. |
| 71 |
@NonNull |
| 72 |
private final ImmutableList<XmlAttribute> mAttributes; |
| 73 |
|
| 74 |
// map of all tools related attributes keyed by target attribute name |
| 75 |
@NonNull |
| 76 |
private final Map<NodeName, AttributeOperationType> mAttributesOperationTypes; |
| 77 |
|
| 78 |
// list of mergeable children elements. |
| 79 |
@NonNull |
| 80 |
private final ImmutableList<XmlElement> mMergeableChildren; |
| 81 |
|
| 82 |
// optional selector declared on this xml element. |
| 83 |
@Nullable |
| 84 |
private final Selector mSelector; |
| 85 |
|
| 86 |
// optional list of libraries that we should ignore the minSdk version |
| 87 |
@NonNull |
| 88 |
private final List<Selector> mOverrideUsesSdkLibrarySelectors; |
| 89 |
|
| 90 |
|
| 91 |
public XmlElement(@NonNull Element xml, @NonNull XmlDocument document) { |
| 92 |
super(xml); |
| 93 |
|
| 94 |
mDocument = Preconditions.checkNotNull(document); |
| 95 |
Selector selector = null; |
| 96 |
List<Selector> overrideUsesSdkLibrarySelectors = ImmutableList.of(); |
| 97 |
|
| 98 |
ImmutableMap.Builder<NodeName, AttributeOperationType> attributeOperationTypeBuilder = |
| 99 |
ImmutableMap.builder(); |
| 100 |
ImmutableList.Builder<XmlAttribute> attributesListBuilder = ImmutableList.builder(); |
| 101 |
NamedNodeMap namedNodeMap = getXml().getAttributes(); |
| 102 |
NodeOperationType lastNodeOperationType = null; |
| 103 |
for (int i = 0; i < namedNodeMap.getLength(); i++) { |
| 104 |
Node attribute = namedNodeMap.item(i); |
| 105 |
if (SdkConstants.TOOLS_URI.equals(attribute.getNamespaceURI())) { |
| 106 |
String instruction = attribute.getLocalName(); |
| 107 |
if (instruction.equals(NodeOperationType.NODE_LOCAL_NAME)) { |
| 108 |
// should we flag an error when there are more than one operation type on a node ? |
| 109 |
lastNodeOperationType = NodeOperationType.valueOf( |
| 110 |
SdkUtils.camelCaseToConstantName( |
| 111 |
attribute.getNodeValue())); |
| 112 |
} else if (instruction.equals(Selector.SELECTOR_LOCAL_NAME)) { |
| 113 |
selector = new Selector(attribute.getNodeValue()); |
| 114 |
} else if (instruction.equals(NodeOperationType.OVERRIDE_USES_SDK)) { |
| 115 |
String nodeValue = attribute.getNodeValue(); |
| 116 |
ImmutableList.Builder<Selector> builder = ImmutableList.builder(); |
| 117 |
for (String selectorValue : Splitter.on(',').split(nodeValue)) { |
| 118 |
builder.add(new Selector(selectorValue.trim())); |
| 119 |
} |
| 120 |
overrideUsesSdkLibrarySelectors = builder.build(); |
| 121 |
} else { |
| 122 |
AttributeOperationType attributeOperationType; |
| 123 |
try { |
| 124 |
attributeOperationType = |
| 125 |
AttributeOperationType.valueOf( |
| 126 |
SdkUtils.xmlNameToConstantName(instruction)); |
| 127 |
} catch (IllegalArgumentException e) { |
| 128 |
try { |
| 129 |
// is this another tool's operation type that we do not care about. |
| 130 |
OtherOperationType.valueOf(instruction); |
| 131 |
break; |
| 132 |
} catch (IllegalArgumentException e1) { |
| 133 |
|
| 134 |
String errorMessage = |
| 135 |
String.format("Invalid instruction '%1$s', " |
| 136 |
+ "valid instructions are : %2$s", |
| 137 |
instruction, |
| 138 |
Joiner.on(',').join(AttributeOperationType.values()) |
| 139 |
); |
| 140 |
throw new RuntimeException(MergingException.wrapException(e) |
| 141 |
.withMessage(errorMessage) |
| 142 |
.withFile(mDocument.getSourceFile()) |
| 143 |
.withPosition(XmlDocument.getNodePosition(xml)).build()); |
| 144 |
} |
| 145 |
} |
| 146 |
for (String attributeName : Splitter.on(',').trimResults() |
| 147 |
.split(attribute.getNodeValue())) { |
| 148 |
if (attributeName.indexOf(XmlUtils.NS_SEPARATOR) == -1) { |
| 149 |
String toolsPrefix = XmlUtils |
| 150 |
.lookupNamespacePrefix(getXml(), SdkConstants.TOOLS_URI, |
| 151 |
SdkConstants.ANDROID_NS_NAME, false); |
| 152 |
// automatically provide the prefix. |
| 153 |
attributeName = toolsPrefix + XmlUtils.NS_SEPARATOR + attributeName; |
| 154 |
} |
| 155 |
NodeName nodeName = XmlNode.fromXmlName(attributeName); |
| 156 |
attributeOperationTypeBuilder.put(nodeName, attributeOperationType); |
| 157 |
} |
| 158 |
} |
| 159 |
} |
| 160 |
} |
| 161 |
mAttributesOperationTypes = attributeOperationTypeBuilder.build(); |
| 162 |
for (int i = 0; i < namedNodeMap.getLength(); i++) { |
| 163 |
Node attribute = namedNodeMap.item(i); |
| 164 |
XmlAttribute xmlAttribute = new XmlAttribute( |
| 165 |
this, (Attr) attribute, getType().getAttributeModel(XmlNode.fromXmlName( |
| 166 |
((Attr) attribute).getName()))); |
| 167 |
attributesListBuilder.add(xmlAttribute); |
| 168 |
} |
| 169 |
mNodeOperationType = lastNodeOperationType; |
| 170 |
mAttributes = attributesListBuilder.build(); |
| 171 |
mMergeableChildren = initMergeableChildren(); |
| 172 |
mSelector = selector; |
| 173 |
mOverrideUsesSdkLibrarySelectors = overrideUsesSdkLibrarySelectors; |
| 174 |
} |
| 175 |
|
| 176 |
/** |
| 177 |
* Returns the owning {@link com.android.manifmerger.XmlDocument} |
| 178 |
*/ |
| 179 |
@NonNull |
| 180 |
public XmlDocument getDocument() { |
| 181 |
return mDocument; |
| 182 |
} |
| 183 |
|
| 184 |
/** |
| 185 |
* Returns the list of attributes for this xml element. |
| 186 |
*/ |
| 187 |
public List<XmlAttribute> getAttributes() { |
| 188 |
return mAttributes; |
| 189 |
} |
| 190 |
|
| 191 |
/** |
| 192 |
* Returns the {@link com.android.manifmerger.XmlAttribute} for an attribute present on this |
| 193 |
* xml element, or {@link com.google.common.base.Optional#absent} if not present. |
| 194 |
* @param attributeName the attribute name. |
| 195 |
*/ |
| 196 |
public Optional<XmlAttribute> getAttribute(NodeName attributeName) { |
| 197 |
for (XmlAttribute xmlAttribute : mAttributes) { |
| 198 |
if (xmlAttribute.getName().equals(attributeName)) { |
| 199 |
return Optional.of(xmlAttribute); |
| 200 |
} |
| 201 |
} |
| 202 |
return Optional.absent(); |
| 203 |
} |
| 204 |
|
| 205 |
/** |
| 206 |
* Get the node operation type as optionally specified by the user. If the user did not |
| 207 |
* explicitly specify how conflicting elements should be handled, a |
| 208 |
* {@link com.android.manifmerger.NodeOperationType#MERGE} will be returned. |
| 209 |
*/ |
| 210 |
@NonNull |
| 211 |
public NodeOperationType getOperationType() { |
| 212 |
return mNodeOperationType != null |
| 213 |
? mNodeOperationType |
| 214 |
: NodeOperationType.MERGE; |
| 215 |
} |
| 216 |
|
| 217 |
/** |
| 218 |
* Get the attribute operation type as optionally specified by the user. If the user did not |
| 219 |
* explicitly specify how conflicting attributes should be handled, a |
| 220 |
* {@link AttributeOperationType#STRICT} will be returned. |
| 221 |
*/ |
| 222 |
@NonNull |
| 223 |
public AttributeOperationType getAttributeOperationType(NodeName attributeName) { |
| 224 |
return mAttributesOperationTypes.containsKey(attributeName) |
| 225 |
? mAttributesOperationTypes.get(attributeName) |
| 226 |
: AttributeOperationType.STRICT; |
| 227 |
} |
| 228 |
|
| 229 |
@NonNull |
| 230 |
public Collection<Map.Entry<NodeName, AttributeOperationType>> getAttributeOperations() { |
| 231 |
return mAttributesOperationTypes.entrySet(); |
| 232 |
} |
| 233 |
|
| 234 |
@NonNull |
| 235 |
public List<Selector> getOverrideUsesSdkLibrarySelectors() { |
| 236 |
return mOverrideUsesSdkLibrarySelectors; |
| 237 |
} |
| 238 |
|
| 239 |
|
| 240 |
@NonNull |
| 241 |
@Override |
| 242 |
public SourcePosition getPosition() { |
| 243 |
return XmlDocument.getNodePosition(this); |
| 244 |
} |
| 245 |
|
| 246 |
@NonNull |
| 247 |
@Override |
| 248 |
public SourceFile getSourceFile() { |
| 249 |
return mDocument.getSourceFile(); |
| 250 |
} |
| 251 |
|
| 252 |
|
| 253 |
/** |
| 254 |
* Merge this xml element with a lower priority node. |
| 255 |
* |
| 256 |
* For now, attributes will be merged. If present on both xml elements, a warning will be |
| 257 |
* issued and the attribute merge will be rejected. |
| 258 |
* |
| 259 |
* @param lowerPriorityNode lower priority Xml element to merge with. |
| 260 |
* @param mergingReport the merging report to log errors and actions. |
| 261 |
*/ |
| 262 |
public void mergeWithLowerPriorityNode( |
| 263 |
@NonNull XmlElement lowerPriorityNode, |
| 264 |
@NonNull MergingReport.Builder mergingReport) { |
| 265 |
|
| 266 |
|
| 267 |
if (mSelector != null && !mSelector.isResolvable(getDocument().getSelectors())) { |
| 268 |
mergingReport.addMessage(getSourceFilePosition(), |
| 269 |
MergingReport.Record.Severity.ERROR, |
| 270 |
String.format("'tools:selector=\"%1$s\"' is not a valid library identifier, " |
| 271 |
+ "valid identifiers are : %2$s", |
| 272 |
mSelector.toString(), |
| 273 |
Joiner.on(',').join(mDocument.getSelectors().getKeys()))); |
| 274 |
return; |
| 275 |
|
| 276 |
} |
| 277 |
mergingReport.getLogger().info("Merging " + getId() |
| 278 |
+ " with lower " + lowerPriorityNode.printPosition()); |
| 279 |
|
| 280 |
// workaround for 0.12 release and overlay treatment of manifest entries. This will |
| 281 |
// need to be expressed in the model instead. |
| 282 |
MergeType mergeType = getType().getMergeType(); |
| 283 |
// if element we are merging in is not a library (an overlay or an application), we should |
| 284 |
// always merge the <manifest> attributes otherwise, we do not merge the libraries |
| 285 |
// <manifest> attributes. |
| 286 |
if (isA(ManifestModel.NodeTypes.MANIFEST) |
| 287 |
&& lowerPriorityNode.getDocument().getFileType() != XmlDocument.Type.LIBRARY) { |
| 288 |
mergeType = MergeType.MERGE; |
| 289 |
} |
| 290 |
|
| 291 |
if (mergeType != MergeType.MERGE_CHILDREN_ONLY) { |
| 292 |
// make a copy of all the attributes metadata, it will eliminate elements from this |
| 293 |
// list as it finds them explicitly defined in the lower priority node. |
| 294 |
// At the end of the explicit attributes processing, the remaining elements of this |
| 295 |
// list will need to be checked for default value that may clash with a locally |
| 296 |
// defined attribute. |
| 297 |
List<AttributeModel> attributeModels = |
| 298 |
new ArrayList<AttributeModel>(lowerPriorityNode.getType().getAttributeModels()); |
| 299 |
|
| 300 |
// merge explicit attributes from lower priority node. |
| 301 |
for (XmlAttribute lowerPriorityAttribute : lowerPriorityNode.getAttributes()) { |
| 302 |
lowerPriorityAttribute.mergeInHigherPriorityElement(this, mergingReport); |
| 303 |
if (lowerPriorityAttribute.getModel() != null) { |
| 304 |
attributeModels.remove(lowerPriorityAttribute.getModel()); |
| 305 |
} |
| 306 |
} |
| 307 |
// merge implicit default values from lower priority node when we have an explicit |
| 308 |
// attribute declared on this node. |
| 309 |
for (AttributeModel attributeModel : attributeModels) { |
| 310 |
if (attributeModel.getDefaultValue() != null) { |
| 311 |
Optional<XmlAttribute> myAttribute = getAttribute(attributeModel.getName()); |
| 312 |
if (myAttribute.isPresent()) { |
| 313 |
myAttribute.get().mergeWithLowerPriorityDefaultValue( |
| 314 |
mergingReport, lowerPriorityNode); |
| 315 |
} |
| 316 |
} |
| 317 |
} |
| 318 |
} |
| 319 |
// are we supposed to merge children ? |
| 320 |
if (mNodeOperationType != NodeOperationType.MERGE_ONLY_ATTRIBUTES) { |
| 321 |
mergeChildren(lowerPriorityNode, mergingReport); |
| 322 |
} else { |
| 323 |
// record rejection of the lower priority node's children . |
| 324 |
for (XmlElement lowerPriorityChild : lowerPriorityNode.getMergeableElements()) { |
| 325 |
mergingReport.getActionRecorder().recordNodeAction(this, |
| 326 |
Actions.ActionType.REJECTED, |
| 327 |
lowerPriorityChild); |
| 328 |
} |
| 329 |
} |
| 330 |
} |
| 331 |
|
| 332 |
@NonNull |
| 333 |
public ImmutableList<XmlElement> getMergeableElements() { |
| 334 |
return mMergeableChildren; |
| 335 |
} |
| 336 |
|
| 337 |
/** |
| 338 |
* Returns a child of a particular type and a particular key. |
| 339 |
* @param type the requested child type. |
| 340 |
* @param keyValue the requested child key. |
| 341 |
* @return the child of {@link com.google.common.base.Optional#absent()} if no child of this |
| 342 |
* type and key exist. |
| 343 |
*/ |
| 344 |
@NonNull |
| 345 |
public Optional<XmlElement> getNodeByTypeAndKey( |
| 346 |
ManifestModel.NodeTypes type, |
| 347 |
@Nullable String keyValue) { |
| 348 |
|
| 349 |
for (XmlElement xmlElement : mMergeableChildren) { |
| 350 |
if (xmlElement.isA(type) && |
| 351 |
(keyValue == null || keyValue.equals(xmlElement.getKey()))) { |
| 352 |
return Optional.of(xmlElement); |
| 353 |
} |
| 354 |
} |
| 355 |
return Optional.absent(); |
| 356 |
} |
| 357 |
|
| 358 |
/** |
| 359 |
* Returns all immediate children of this node for a particular type, irrespective of their |
| 360 |
* key. |
| 361 |
* @param type the type of children element requested. |
| 362 |
* @return the list (potentially empty) of children. |
| 363 |
*/ |
| 364 |
@NonNull |
| 365 |
public ImmutableList<XmlElement> getAllNodesByType(ManifestModel.NodeTypes type) { |
| 366 |
ImmutableList.Builder<XmlElement> listBuilder = ImmutableList.builder(); |
| 367 |
for (XmlElement mergeableChild : initMergeableChildren()) { |
| 368 |
if (mergeableChild.isA(type)) { |
| 369 |
listBuilder.add(mergeableChild); |
| 370 |
} |
| 371 |
} |
| 372 |
return listBuilder.build(); |
| 373 |
} |
| 374 |
|
| 375 |
// merge this higher priority node with a lower priority node. |
| 376 |
public void mergeChildren(@NonNull XmlElement lowerPriorityNode, |
| 377 |
@NonNull MergingReport.Builder mergingReport) { |
| 378 |
|
| 379 |
// read all lower priority mergeable nodes. |
| 380 |
// if the same node is not defined in this document merge it in. |
| 381 |
// if the same is defined, so far, give an error message. |
| 382 |
for (XmlElement lowerPriorityChild : lowerPriorityNode.getMergeableElements()) { |
| 383 |
|
| 384 |
if (shouldIgnore(lowerPriorityChild, mergingReport)) { |
| 385 |
continue; |
| 386 |
} |
| 387 |
mergeChild(lowerPriorityChild, mergingReport); |
| 388 |
} |
| 389 |
} |
| 390 |
|
| 391 |
/** |
| 392 |
* Returns true if this element supports having a tools:selector decoration, false otherwise. |
| 393 |
*/ |
| 394 |
public boolean supportsSelector() { |
| 395 |
return getOperationType().isSelectable(); |
| 396 |
} |
| 397 |
|
| 398 |
// merge a child of a lower priority node into this higher priority node. |
| 399 |
private void mergeChild(@NonNull XmlElement lowerPriorityChild, @NonNull MergingReport.Builder mergingReport) { |
| 400 |
|
| 401 |
ILogger logger = mergingReport.getLogger(); |
| 402 |
|
| 403 |
// If this a custom element, we just blindly merge it in. |
| 404 |
if (lowerPriorityChild.getType() == ManifestModel.NodeTypes.CUSTOM) { |
| 405 |
handleCustomElement(lowerPriorityChild, mergingReport); |
| 406 |
return; |
| 407 |
} |
| 408 |
|
| 409 |
Optional<XmlElement> thisChildOptional = |
| 410 |
getNodeByTypeAndKey(lowerPriorityChild.getType(),lowerPriorityChild.getKey()); |
| 411 |
|
| 412 |
// only in the lower priority document ? |
| 413 |
if (!thisChildOptional.isPresent()) { |
| 414 |
addElement(lowerPriorityChild, mergingReport); |
| 415 |
return; |
| 416 |
} |
| 417 |
// it's defined in both files. |
| 418 |
logger.verbose(lowerPriorityChild.getId() + " defined in both files..."); |
| 419 |
|
| 420 |
XmlElement thisChild = thisChildOptional.get(); |
| 421 |
switch (thisChild.getType().getMergeType()) { |
| 422 |
case CONFLICT: |
| 423 |
addMessage(mergingReport, MergingReport.Record.Severity.ERROR, String.format( |
| 424 |
"Node %1$s cannot be present in more than one input file and it's " |
| 425 |
+ "present at %2$s and %3$s", |
| 426 |
thisChild.getType(), |
| 427 |
thisChild.printPosition(), |
| 428 |
lowerPriorityChild.printPosition() |
| 429 |
)); |
| 430 |
break; |
| 431 |
case ALWAYS: |
| 432 |
|
| 433 |
// no merging, we consume the lower priority node unmodified. |
| 434 |
// if the two elements are equal, just skip it. |
| 435 |
|
| 436 |
// but check first that we are not supposed to replace or remove it. |
| 437 |
@NonNull NodeOperationType operationType = |
| 438 |
calculateNodeOperationType(thisChild, lowerPriorityChild); |
| 439 |
if (operationType == NodeOperationType.REMOVE || |
| 440 |
operationType == NodeOperationType.REPLACE) { |
| 441 |
mergingReport.getActionRecorder().recordNodeAction(thisChild, |
| 442 |
Actions.ActionType.REJECTED, lowerPriorityChild); |
| 443 |
break; |
| 444 |
} |
| 445 |
|
| 446 |
if (thisChild.getType().areMultipleDeclarationAllowed()) { |
| 447 |
mergeChildrenWithMultipleDeclarations(lowerPriorityChild, mergingReport); |
| 448 |
} else { |
| 449 |
if (!thisChild.isEquals(lowerPriorityChild)) { |
| 450 |
addElement(lowerPriorityChild, mergingReport); |
| 451 |
} |
| 452 |
} |
| 453 |
break; |
| 454 |
default: |
| 455 |
// 2 nodes exist, some merging need to happen |
| 456 |
handleTwoElementsExistence(thisChild, lowerPriorityChild, mergingReport); |
| 457 |
break; |
| 458 |
} |
| 459 |
} |
| 460 |
|
| 461 |
/** |
| 462 |
* Handles presence of custom elements (elements not part of the android or tools |
| 463 |
* namespaces). Such elements are merged unchanged into the resulting document, and |
| 464 |
* optionally, the namespace definition is added to the merged document root element. |
| 465 |
* @param customElement the custom element present in the lower priority document. |
| 466 |
* @param mergingReport the merging report to log errors and actions. |
| 467 |
*/ |
| 468 |
private void handleCustomElement(@NonNull XmlElement customElement, |
| 469 |
@NonNull MergingReport.Builder mergingReport) { |
| 470 |
addElement(customElement, mergingReport); |
| 471 |
|
| 472 |
// add the custom namespace to the document generation. |
| 473 |
String nodeName = customElement.getXml().getNodeName(); |
| 474 |
if (!nodeName.contains(":")) { |
| 475 |
return; |
| 476 |
} |
| 477 |
@NonNull String prefix = nodeName.substring(0, nodeName.indexOf(':')); |
| 478 |
String namespace = customElement.getDocument().getRootNode() |
| 479 |
.getXml().getAttribute(SdkConstants.XMLNS_PREFIX + prefix); |
| 480 |
|
| 481 |
if (namespace != null) { |
| 482 |
getDocument().getRootNode().getXml().setAttributeNS( |
| 483 |
SdkConstants.XMLNS_URI, SdkConstants.XMLNS_PREFIX + prefix, namespace); |
| 484 |
} |
| 485 |
} |
| 486 |
|
| 487 |
/** |
| 488 |
* Merges two children when this children's type allow multiple elements declaration with the |
| 489 |
* same key value. In that case, we only merge the lower priority child if there is not already |
| 490 |
* an element with the same key value that is equal to the lower priority child. Two children |
| 491 |
* are equals if they have the same attributes and children declared irrespective of the |
| 492 |
* declaration order. |
| 493 |
* |
| 494 |
* @param lowerPriorityChild the lower priority element's child. |
| 495 |
* @param mergingReport the merging report to log errors and actions. |
| 496 |
*/ |
| 497 |
private void mergeChildrenWithMultipleDeclarations( |
| 498 |
@NonNull XmlElement lowerPriorityChild, |
| 499 |
@NonNull MergingReport.Builder mergingReport) { |
| 500 |
|
| 501 |
Preconditions.checkArgument(lowerPriorityChild.getType().areMultipleDeclarationAllowed()); |
| 502 |
if (lowerPriorityChild.getType().areMultipleDeclarationAllowed()) { |
| 503 |
for (XmlElement sameTypeChild : getAllNodesByType(lowerPriorityChild.getType())) { |
| 504 |
if (sameTypeChild.getId().equals(lowerPriorityChild.getId()) && |
| 505 |
sameTypeChild.isEquals(lowerPriorityChild)) { |
| 506 |
return; |
| 507 |
} |
| 508 |
} |
| 509 |
} |
| 510 |
// if we end up here, we never found a child of this element with the same key and strictly |
| 511 |
// equals to the lowerPriorityChild so we should merge it in. |
| 512 |
addElement(lowerPriorityChild, mergingReport); |
| 513 |
} |
| 514 |
|
| 515 |
/** |
| 516 |
* Determine if we should completely ignore a child from any merging activity. |
| 517 |
* There are 2 situations where we should ignore a lower priority child : |
| 518 |
* <p> |
| 519 |
* <ul> |
| 520 |
* <li>The associate {@link com.android.manifmerger.ManifestModel.NodeTypes} is |
| 521 |
* annotated with {@link com.android.manifmerger.MergeType#IGNORE}</li> |
| 522 |
* <li>This element has a child of the same type with no key that has a ' |
| 523 |
* tools:node="removeAll' attribute.</li> |
| 524 |
* </ul> |
| 525 |
* @param lowerPriorityChild the lower priority child we should determine eligibility for |
| 526 |
* merging. |
| 527 |
* @return true if the element should be ignored, false otherwise. |
| 528 |
*/ |
| 529 |
private boolean shouldIgnore( |
| 530 |
@NonNull XmlElement lowerPriorityChild, |
| 531 |
@NonNull MergingReport.Builder mergingReport) { |
| 532 |
|
| 533 |
if (lowerPriorityChild.getType().getMergeType() == MergeType.IGNORE) { |
| 534 |
return true; |
| 535 |
} |
| 536 |
|
| 537 |
// do we have an element of the same type of that child with no key ? |
| 538 |
Optional<XmlElement> thisChildElementOptional = |
| 539 |
getNodeByTypeAndKey(lowerPriorityChild.getType(), null /* keyValue */); |
| 540 |
if (!thisChildElementOptional.isPresent()) { |
| 541 |
return false; |
| 542 |
} |
| 543 |
XmlElement thisChild = thisChildElementOptional.get(); |
| 544 |
|
| 545 |
// are we supposed to delete all occurrences and if yes, is there a selector defined to |
| 546 |
// filter which elements should be deleted. |
| 547 |
boolean shouldDelete = thisChild.mNodeOperationType == NodeOperationType.REMOVE_ALL |
| 548 |
&& (thisChild.mSelector == null |
| 549 |
|| thisChild.mSelector.appliesTo(lowerPriorityChild)); |
| 550 |
// if we should discard this child element, record the action. |
| 551 |
if (shouldDelete) { |
| 552 |
mergingReport.getActionRecorder().recordNodeAction(thisChildElementOptional.get(), |
| 553 |
Actions.ActionType.REJECTED, |
| 554 |
lowerPriorityChild); |
| 555 |
} |
| 556 |
return shouldDelete; |
| 557 |
} |
| 558 |
|
| 559 |
/** |
| 560 |
* Handle 2 elements (of same identity) merging. |
| 561 |
* higher priority one has a tools:node="remove", remove the low priority one |
| 562 |
* higher priority one has a tools:node="replace", replace the low priority one |
| 563 |
* higher priority one has a tools:node="strict", flag the error if not equals. |
| 564 |
* default or tools:node="merge", merge the two elements. |
| 565 |
* @param higherPriority the higher priority node. |
| 566 |
* @param lowerPriority the lower priority element. |
| 567 |
* @param mergingReport the merging report to log errors and actions. |
| 568 |
*/ |
| 569 |
private void handleTwoElementsExistence( |
| 570 |
@NonNull XmlElement higherPriority, |
| 571 |
@NonNull XmlElement lowerPriority, |
| 572 |
@NonNull MergingReport.Builder mergingReport) { |
| 573 |
|
| 574 |
@NonNull NodeOperationType operationType = calculateNodeOperationType(higherPriority, lowerPriority); |
| 575 |
// 2 nodes exist, 3 possibilities : |
| 576 |
// higher priority one has a tools:node="remove", remove the low priority one |
| 577 |
// higher priority one has a tools:node="replace", replace the low priority one |
| 578 |
// higher priority one has a tools:node="strict", flag the error if not equals. |
| 579 |
switch(operationType) { |
| 580 |
case MERGE: |
| 581 |
case MERGE_ONLY_ATTRIBUTES: |
| 582 |
// record the action |
| 583 |
mergingReport.getActionRecorder().recordNodeAction(higherPriority, |
| 584 |
Actions.ActionType.MERGED, lowerPriority); |
| 585 |
// and perform the merge |
| 586 |
higherPriority.mergeWithLowerPriorityNode(lowerPriority, mergingReport); |
| 587 |
break; |
| 588 |
case REMOVE: |
| 589 |
case REPLACE: |
| 590 |
// so far remove and replace and similar, the post validation will take |
| 591 |
// care of removing this node in the case of REMOVE. |
| 592 |
|
| 593 |
// just don't import the lower priority node and record the action. |
| 594 |
mergingReport.getActionRecorder().recordNodeAction(higherPriority, |
| 595 |
Actions.ActionType.REJECTED, lowerPriority); |
| 596 |
break; |
| 597 |
case STRICT: |
| 598 |
Optional<String> compareMessage = higherPriority.compareTo(lowerPriority); |
| 599 |
if (compareMessage.isPresent()) { |
| 600 |
// flag error. |
| 601 |
addMessage(mergingReport, MergingReport.Record.Severity.ERROR, String.format( |
| 602 |
"Node %1$s at %2$s is tagged with tools:node=\"strict\", yet " |
| 603 |
+ "%3$s at %4$s is different : %5$s", |
| 604 |
higherPriority.getId(), |
| 605 |
higherPriority.printPosition(), |
| 606 |
lowerPriority.getId(), |
| 607 |
lowerPriority.printPosition(), |
| 608 |
compareMessage.get() |
| 609 |
)); |
| 610 |
} |
| 611 |
break; |
| 612 |
default: |
| 613 |
mergingReport.getLogger().error(null /* throwable */, |
| 614 |
"Unhandled node operation type %s", higherPriority.getOperationType()); |
| 615 |
break; |
| 616 |
} |
| 617 |
} |
| 618 |
|
| 619 |
/** |
| 620 |
* Calculate the effective node operation type for a higher priority node when a lower priority |
| 621 |
* node is queried for merge. |
| 622 |
* @param higherPriority the higher priority node which may have a {@link NodeOperationType} |
| 623 |
* declaration and may also have a {@link Selector} declaration. |
| 624 |
* @param lowerPriority the lower priority node that is elected for merging with the higher |
| 625 |
* priority node. |
| 626 |
* @return the effective {@link NodeOperationType} that should be used to affect higher and |
| 627 |
* lower priority nodes merging. |
| 628 |
*/ |
| 629 |
@NonNull |
| 630 |
private static NodeOperationType calculateNodeOperationType( |
| 631 |
@NonNull XmlElement higherPriority, |
| 632 |
@NonNull XmlElement lowerPriority) { |
| 633 |
|
| 634 |
@NonNull NodeOperationType operationType = higherPriority.getOperationType(); |
| 635 |
// if the operation's selector exists and the lower priority node is not selected, |
| 636 |
// we revert to default operation type which is merge. |
| 637 |
if (higherPriority.supportsSelector() |
| 638 |
&& higherPriority.mSelector != null |
| 639 |
&& !higherPriority.mSelector.appliesTo(lowerPriority)) { |
| 640 |
operationType = NodeOperationType.MERGE; |
| 641 |
} |
| 642 |
return operationType; |
| 643 |
} |
| 644 |
|
| 645 |
/** |
| 646 |
* Add an element and its leading comments as the last sub-element of the current element. |
| 647 |
* @param elementToBeAdded xml element to be added to the current element. |
| 648 |
* @param mergingReport the merging report to log errors and actions. |
| 649 |
*/ |
| 650 |
private void addElement( |
| 651 |
@NonNull XmlElement elementToBeAdded, @NonNull MergingReport.Builder mergingReport) { |
| 652 |
|
| 653 |
List<Node> comments = getLeadingComments(elementToBeAdded.getXml()); |
| 654 |
// record all the actions before the node is moved from the library document to the main |
| 655 |
// merged document. |
| 656 |
mergingReport.getActionRecorder().recordDefaultNodeAction(elementToBeAdded); |
| 657 |
|
| 658 |
// only in the new file, just import it. |
| 659 |
Node node = getXml().getOwnerDocument().adoptNode(elementToBeAdded.getXml()); |
| 660 |
getXml().appendChild(node); |
| 661 |
|
| 662 |
// also adopt the child's comments if any. |
| 663 |
for (Node comment : comments) { |
| 664 |
Node newComment = getXml().getOwnerDocument().adoptNode(comment); |
| 665 |
getXml().insertBefore(newComment, node); |
| 666 |
} |
| 667 |
|
| 668 |
mergingReport.getLogger().verbose("Adopted " + node); |
| 669 |
} |
| 670 |
|
| 671 |
public boolean isEquals(XmlElement otherNode) { |
| 672 |
return !compareTo(otherNode).isPresent(); |
| 673 |
} |
| 674 |
|
| 675 |
/** |
| 676 |
* Returns a potentially null (if not present) selector decoration on this element. |
| 677 |
*/ |
| 678 |
@Nullable |
| 679 |
public Selector getSelector() { |
| 680 |
return mSelector; |
| 681 |
} |
| 682 |
|
| 683 |
/** |
| 684 |
* Compares this element with another {@link XmlElement} ignoring all attributes belonging to |
| 685 |
* the {@link com.android.SdkConstants#TOOLS_URI} namespace. |
| 686 |
* |
| 687 |
* @param other the other element to compare against. |
| 688 |
* @return a {@link String} describing the differences between the two XML elements or |
| 689 |
* {@link Optional#absent()} if they are equals. |
| 690 |
*/ |
| 691 |
@NonNull |
| 692 |
public Optional<String> compareTo(Object other) { |
| 693 |
|
| 694 |
if (!(other instanceof XmlElement)) { |
| 695 |
return Optional.of("Wrong type"); |
| 696 |
} |
| 697 |
XmlElement otherNode = (XmlElement) other; |
| 698 |
|
| 699 |
// compare element names |
| 700 |
if (getXml().getNamespaceURI() != null) { |
| 701 |
if (!getXml().getLocalName().equals(otherNode.getXml().getLocalName())) { |
| 702 |
return Optional.of( |
| 703 |
String.format("Element names do not match: %1$s versus %2$s", |
| 704 |
getXml().getLocalName(), |
| 705 |
otherNode.getXml().getLocalName())); |
| 706 |
} |
| 707 |
// compare element ns |
| 708 |
String thisNS = getXml().getNamespaceURI(); |
| 709 |
String otherNS = otherNode.getXml().getNamespaceURI(); |
| 710 |
if ((thisNS == null && otherNS != null) |
| 711 |
|| (thisNS != null && !thisNS.equals(otherNS))) { |
| 712 |
return Optional.of( |
| 713 |
String.format("Element namespaces names do not match: %1$s versus %2$s", |
| 714 |
thisNS, otherNS)); |
| 715 |
} |
| 716 |
} else { |
| 717 |
if (!getXml().getNodeName().equals(otherNode.getXml().getNodeName())) { |
| 718 |
return Optional.of(String.format("Element names do not match: %1$s versus %2$s", |
| 719 |
getXml().getNodeName(), |
| 720 |
otherNode.getXml().getNodeName())); |
| 721 |
} |
| 722 |
} |
| 723 |
|
| 724 |
// compare attributes, we do it twice to identify added/missing elements in both lists. |
| 725 |
Optional<String> message = checkAttributes(this, otherNode); |
| 726 |
if (message.isPresent()) { |
| 727 |
return message; |
| 728 |
} |
| 729 |
message = checkAttributes(otherNode, this); |
| 730 |
if (message.isPresent()) { |
| 731 |
return message; |
| 732 |
} |
| 733 |
|
| 734 |
// compare children |
| 735 |
@NonNull List<Node> expectedChildren = filterUninterestingNodes(getXml().getChildNodes()); |
| 736 |
@NonNull List<Node> actualChildren = filterUninterestingNodes(otherNode.getXml().getChildNodes()); |
| 737 |
if (expectedChildren.size() != actualChildren.size()) { |
| 738 |
|
| 739 |
if (expectedChildren.size() > actualChildren.size()) { |
| 740 |
// missing some. |
| 741 |
@NonNull List<String> missingChildrenNames = |
| 742 |
Lists.transform(expectedChildren, NODE_TO_NAME); |
| 743 |
missingChildrenNames.removeAll(Lists.transform(actualChildren, NODE_TO_NAME)); |
| 744 |
return Optional.of(String.format( |
| 745 |
"%1$s: Number of children do not match up: " |
| 746 |
+ "expected %2$d versus %3$d at %4$s, missing %5$s", |
| 747 |
getId(), |
| 748 |
expectedChildren.size(), |
| 749 |
actualChildren.size(), |
| 750 |
otherNode.printPosition(), |
| 751 |
Joiner.on(",").join(missingChildrenNames))); |
| 752 |
} else { |
| 753 |
// extra ones. |
| 754 |
@NonNull List<String> extraChildrenNames = Lists.transform(actualChildren, NODE_TO_NAME); |
| 755 |
extraChildrenNames.removeAll(Lists.transform(expectedChildren, NODE_TO_NAME)); |
| 756 |
return Optional.of(String.format( |
| 757 |
"%1$s: Number of children do not match up: " |
| 758 |
+ "expected %2$d versus %3$d at %4$s, extra elements found : %5$s", |
| 759 |
getId(), |
| 760 |
expectedChildren.size(), |
| 761 |
actualChildren.size(), |
| 762 |
otherNode.printPosition(), |
| 763 |
Joiner.on(",").join(expectedChildren))); |
| 764 |
} |
| 765 |
} |
| 766 |
for (Node expectedChild : expectedChildren) { |
| 767 |
if (expectedChild.getNodeType() == Node.ELEMENT_NODE) { |
| 768 |
@NonNull XmlElement expectedChildNode = new XmlElement((Element) expectedChild, mDocument); |
| 769 |
message = findAndCompareNode(otherNode, actualChildren, expectedChildNode); |
| 770 |
if (message.isPresent()) { |
| 771 |
return message; |
| 772 |
} |
| 773 |
} |
| 774 |
} |
| 775 |
return Optional.absent(); |
| 776 |
} |
| 777 |
|
| 778 |
private Optional<String> findAndCompareNode( |
| 779 |
@NonNull XmlElement otherElement, |
| 780 |
@NonNull List<Node> otherElementChildren, |
| 781 |
@NonNull XmlElement childNode) { |
| 782 |
|
| 783 |
Optional<String> message = Optional.absent(); |
| 784 |
for (Node potentialNode : otherElementChildren) { |
| 785 |
if (potentialNode.getNodeType() == Node.ELEMENT_NODE) { |
| 786 |
@NonNull XmlElement otherChildNode = new XmlElement((Element) potentialNode, mDocument); |
| 787 |
if (childNode.getType() == otherChildNode.getType()) { |
| 788 |
// check if this element uses a key. |
| 789 |
if (childNode.getType().getNodeKeyResolver().getKeyAttributesNames() |
| 790 |
.isEmpty()) { |
| 791 |
// no key... try all the other elements, if we find one equal, we are done. |
| 792 |
message = childNode.compareTo(otherChildNode); |
| 793 |
if (!message.isPresent()) { |
| 794 |
return Optional.absent(); |
| 795 |
} |
| 796 |
} else { |
| 797 |
// key... |
| 798 |
if (childNode.getKey() == null) { |
| 799 |
// other key MUST also be null. |
| 800 |
if (otherChildNode.getKey() == null) { |
| 801 |
return childNode.compareTo(otherChildNode); |
| 802 |
} |
| 803 |
} else { |
| 804 |
if (childNode.getKey().equals(otherChildNode.getKey())) { |
| 805 |
return childNode.compareTo(otherChildNode); |
| 806 |
} |
| 807 |
} |
| 808 |
} |
| 809 |
} |
| 810 |
} |
| 811 |
} |
| 812 |
return message.isPresent() |
| 813 |
? message |
| 814 |
: Optional.of(String.format("Child %1$s not found in document %2$s", |
| 815 |
childNode.getId(), |
| 816 |
otherElement.printPosition())); |
| 817 |
} |
| 818 |
|
| 819 |
@NonNull |
| 820 |
private static List<Node> filterUninterestingNodes(@NonNull NodeList nodeList) { |
| 821 |
List<Node> interestingNodes = new ArrayList<Node>(); |
| 822 |
for (int i = 0; i < nodeList.getLength(); i++) { |
| 823 |
Node node = nodeList.item(i); |
| 824 |
if (node.getNodeType() == Node.TEXT_NODE) { |
| 825 |
Text t = (Text) node; |
| 826 |
if (!t.getData().trim().isEmpty()) { |
| 827 |
interestingNodes.add(node); |
| 828 |
} |
| 829 |
} else if (node.getNodeType() != Node.COMMENT_NODE) { |
| 830 |
interestingNodes.add(node); |
| 831 |
} |
| 832 |
|
| 833 |
} |
| 834 |
return interestingNodes; |
| 835 |
} |
| 836 |
|
| 837 |
private static Optional<String> checkAttributes( |
| 838 |
@NonNull XmlElement expected, |
| 839 |
@NonNull XmlElement actual) { |
| 840 |
|
| 841 |
for (XmlAttribute expectedAttr : expected.getAttributes()) { |
| 842 |
XmlAttribute.NodeName attributeName = expectedAttr.getName(); |
| 843 |
if (attributeName.isInNamespace(SdkConstants.TOOLS_URI)) { |
| 844 |
continue; |
| 845 |
} |
| 846 |
Optional<XmlAttribute> actualAttr = actual.getAttribute(attributeName); |
| 847 |
if (actualAttr.isPresent()) { |
| 848 |
if (!expectedAttr.getValue().equals(actualAttr.get().getValue())) { |
| 849 |
return Optional.of( |
| 850 |
String.format("Attribute %1$s do not match: %2$s versus %3$s at %4$s", |
| 851 |
expectedAttr.getId(), |
| 852 |
expectedAttr.getValue(), |
| 853 |
actualAttr.get().getValue(), |
| 854 |
actual.printPosition())); |
| 855 |
} |
| 856 |
} else { |
| 857 |
return Optional.of(String.format("Attribute %1$s not found at %2$s", |
| 858 |
expectedAttr.getId(), actual.printPosition())); |
| 859 |
} |
| 860 |
} |
| 861 |
return Optional.absent(); |
| 862 |
} |
| 863 |
|
| 864 |
@SuppressWarnings("SpellCheckingInspection") |
| 865 |
private ImmutableList<XmlElement> initMergeableChildren() { |
| 866 |
ImmutableList.Builder<XmlElement> mergeableNodes = new ImmutableList.Builder<XmlElement>(); |
| 867 |
NodeList nodeList = getXml().getChildNodes(); |
| 868 |
for (int i = 0; i < nodeList.getLength(); i++) { |
| 869 |
Node node = nodeList.item(i); |
| 870 |
if (node instanceof Element) { |
| 871 |
XmlElement xmlElement = new XmlElement((Element) node, mDocument); |
| 872 |
mergeableNodes.add(xmlElement); |
| 873 |
} |
| 874 |
} |
| 875 |
return mergeableNodes.build(); |
| 876 |
} |
| 877 |
|
| 878 |
/** |
| 879 |
* Returns all leading comments in the source xml before the node to be adopted. |
| 880 |
* @param nodeToBeAdopted node that will be added as a child to this node. |
| 881 |
*/ |
| 882 |
static List<Node> getLeadingComments(@NonNull Node nodeToBeAdopted) { |
| 883 |
@NonNull ImmutableList.Builder<Node> nodesToAdopt = new ImmutableList.Builder<Node>(); |
| 884 |
Node previousSibling = nodeToBeAdopted.getPreviousSibling(); |
| 885 |
while (previousSibling != null |
| 886 |
&& (previousSibling.getNodeType() == Node.COMMENT_NODE |
| 887 |
|| previousSibling.getNodeType() == Node.TEXT_NODE)) { |
| 888 |
// we really only care about comments. |
| 889 |
if (previousSibling.getNodeType() == Node.COMMENT_NODE) { |
| 890 |
nodesToAdopt.add(previousSibling); |
| 891 |
} |
| 892 |
previousSibling = previousSibling.getPreviousSibling(); |
| 893 |
} |
| 894 |
return nodesToAdopt.build().reverse(); |
| 895 |
} |
| 896 |
|
| 897 |
void addMessage(@NonNull MergingReport.Builder mergingReport, |
| 898 |
@NonNull MergingReport.Record.Severity severity, |
| 899 |
@NonNull String message) { |
| 900 |
mergingReport.addMessage(getSourceFilePosition(), |
| 901 |
severity, |
| 902 |
message); |
| 903 |
} |
| 904 |
} |