- 
                Notifications
    
You must be signed in to change notification settings  - Fork 338
 
[Addition] Added IniRenderer and IniRenderer test cases #137 #149
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
          
     Open
      
      
            Madmegsox1
  wants to merge
  3
  commits into
  apple:main
  
    
      
        
          
  
    
      Choose a base branch
      
     
    
      
        
      
      
        
          
          
        
        
          
            
              
              
              
  
           
        
        
          
            
              
              
           
        
       
     
  
        
          
            
          
            
          
        
       
    
      
from
Madmegsox1:main
  
      
      
   
  
    
  
  
  
 
  
      
    base: main
Could not load branches
            
              
  
    Branch not found: {{ refName }}
  
            
                
      Loading
              
            Could not load tags
            
            
              Nothing to show
            
              
  
            
                
      Loading
              
            Are you sure you want to change the base?
            Some commits from the old base branch may be removed from the timeline,
            and old review comments may become outdated.
          
          
  
     Open
                    Changes from 1 commit
      Commits
    
    
            Show all changes
          
          
            3 commits
          
        
        Select commit
          Hold shift + click to select a range
      
      
    File filter
Filter by extension
Conversations
          Failed to load comments.   
        
        
          
      Loading
        
  Jump to
        
          Jump to file
        
      
      
          Failed to load files.   
        
        
          
      Loading
        
  Diff view
Diff view
There are no files selected for viewing
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,247 @@ | ||
| /** | ||
| * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. | ||
| * | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * | ||
| * https://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
| package org.pkl.core; | ||
| 
     | 
||
| import java.io.IOException; | ||
| import java.io.UncheckedIOException; | ||
| import java.io.Writer; | ||
| import java.util.List; | ||
| import java.util.Map; | ||
| import java.util.Set; | ||
| import java.util.regex.Pattern; | ||
| import org.pkl.core.util.Nullable; | ||
| import org.pkl.core.util.ini.IniUtils; | ||
| 
     | 
||
| // To instantiate this class, use ValueRenderers.properties(). | ||
| final class IniRenderer implements ValueRenderer { | ||
| 
     | 
||
| private final Writer writer; | ||
| private final boolean omitNullProperties; | ||
| private final boolean restrictCharset; | ||
| 
     | 
||
| public IniRenderer(Writer writer, boolean omitNullProperties, boolean restrictCharset) { | ||
| this.writer = writer; | ||
| this.omitNullProperties = omitNullProperties; | ||
| this.restrictCharset = restrictCharset; | ||
| } | ||
| 
     | 
||
| @Override | ||
| public void renderDocument(Object value) { | ||
| new Visitor().renderDocument(value); | ||
| } | ||
| 
     | 
||
| @Override | ||
| public void renderValue(Object value) { | ||
| new Visitor().renderValue(value); | ||
| } | ||
| 
     | 
||
| public class Visitor implements ValueConverter<String> { | ||
| 
     | 
||
| public void renderValue(Object value) { | ||
| write(convert(value), false, restrictCharset); | ||
| } | ||
| 
     | 
||
| public void renderDocument(Object value) { | ||
| if (value instanceof Composite) { | ||
| doVisitMap(null, ((Composite) value).getProperties()); | ||
| } else if (value instanceof Map) { | ||
| doVisitMap(null, (Map<?, ?>) value); | ||
| } else if (value instanceof Pair) { | ||
| Pair<?, ?> pair = (Pair<?, ?>) value; | ||
| doVisitKeyAndValue(null, pair.getFirst(), pair.getSecond()); | ||
| } else { | ||
| throw new RendererException( | ||
| String.format( | ||
| "The top-level value of a Java properties file must have type `Composite`, `Map`, or `Pair`, but got type `%s`.", | ||
| value.getClass().getTypeName())); | ||
| } | ||
| } | ||
| 
     | 
||
| private void doVisitMap(@Nullable String keyPrefix, Map<?, ?> map) { | ||
| for (Map.Entry<?, ?> entry : map.entrySet()) { | ||
| doVisitKeyAndValue(keyPrefix, entry.getKey(), entry.getValue()); | ||
| } | ||
| } | ||
| 
     | 
||
| private void doVisitKeyAndValue(@Nullable String keyPrefix, Object key, Object value) { | ||
| if (omitNullProperties && value instanceof PNull) { | ||
| return; | ||
| } | ||
| var baseKey = convert(key); | ||
| // gets existing key and appends the existing keypreifx if it's not null | ||
| var keyString = keyPrefix == null ? baseKey : keyPrefix + "." + baseKey; | ||
| // discovered a new section and writes key then writes the child values | ||
| // e.g. [example.dog] | ||
| if (value instanceof Composite) { | ||
| writeIniKey(keyString); | ||
| doVisitMap(keyString, ((Composite) value).getProperties()); | ||
| } else if (value instanceof Map) { | ||
| writeIniKey(keyString); | ||
| doVisitMap(keyString, (Map<?, ?>) value); | ||
| } else { | ||
| writeIniValue(baseKey, convert(value)); | ||
| } | ||
| } | ||
| 
     | 
||
| @Override | ||
| public String convertNull() { | ||
| return ""; | ||
| } | ||
| 
     | 
||
| @Override | ||
| public String convertString(String value) { | ||
| return value; | ||
| } | ||
| 
     | 
||
| @Override | ||
| public String convertBoolean(Boolean value) { | ||
| return value.toString(); | ||
| } | ||
| 
     | 
||
| @Override | ||
| public String convertInt(Long value) { | ||
| return value.toString(); | ||
| } | ||
| 
     | 
||
| @Override | ||
| public String convertFloat(Double value) { | ||
| return value.toString(); | ||
| } | ||
| 
     | 
||
| @Override | ||
| public String convertDuration(Duration value) { | ||
| throw new RendererException( | ||
| String.format( | ||
| "Values of type `Duration` cannot be rendered as Properties. Value: %s", value)); | ||
| } | ||
| 
     | 
||
| @Override | ||
| public String convertDataSize(DataSize value) { | ||
| throw new RendererException( | ||
| String.format( | ||
| "Values of type `DateSize` cannot be rendered as Properties. Value: %s", value)); | ||
| } | ||
| 
     | 
||
| @Override | ||
| public String convertPair(Pair<?, ?> value) { | ||
| throw new RendererException( | ||
| String.format( | ||
| "Values of type `Pair` cannot be rendered as Properties. Value: %s", value)); | ||
| } | ||
| 
     | 
||
| @Override | ||
| public String convertList(List<?> value) { | ||
| throw new RendererException( | ||
| String.format( | ||
| "Values of type `List` cannot be rendered as Properties. Value: %s", value)); | ||
| } | ||
| 
     | 
||
| @Override | ||
| public String convertSet(Set<?> value) { | ||
| throw new RendererException( | ||
| String.format("Values of type `Set` cannot be rendered as Properties. Value: %s", value)); | ||
| } | ||
| 
     | 
||
| @Override | ||
| public String convertMap(Map<?, ?> value) { | ||
| throw new RendererException( | ||
| String.format("Values of type `Map` cannot be rendered as Properties. Value: %s", value)); | ||
| } | ||
| 
     | 
||
| @Override | ||
| public String convertObject(PObject value) { | ||
| throw new RendererException( | ||
| String.format( | ||
| "Values of type `Object` cannot be rendered as Properties. Value: %s", value)); | ||
| } | ||
| 
     | 
||
| @Override | ||
| public String convertModule(PModule value) { | ||
| throw new RendererException( | ||
| String.format( | ||
| "Values of type `Module` cannot be rendered as Properties. Value: %s", value)); | ||
| } | ||
| 
     | 
||
| @Override | ||
| public String convertClass(PClass value) { | ||
| throw new RendererException( | ||
| String.format( | ||
| "Values of type `Class` cannot be rendered as Properties. Value: %s", | ||
| value.getSimpleName())); | ||
| } | ||
| 
     | 
||
| @Override | ||
| public String convertTypeAlias(TypeAlias value) { | ||
| throw new RendererException( | ||
| String.format( | ||
| "Values of type `TypeAlias` cannot be rendered as Properties. Value: %s", | ||
| value.getSimpleName())); | ||
| } | ||
| 
     | 
||
| @Override | ||
| public String convertRegex(Pattern value) { | ||
| throw new RendererException( | ||
| String.format( | ||
| "Values of type `Regex` cannot be rendered as Properties. Value: %s", value)); | ||
| } | ||
| 
     | 
||
| private void write(String value, boolean escapeSpace, boolean restrictCharset) { | ||
| try { | ||
| writer.write(IniUtils.renderPropertiesKeyOrValue(value, escapeSpace, restrictCharset)); | ||
| } catch (IOException e) { | ||
| throw new RuntimeException(e); | ||
| } | ||
| } | ||
| 
     | 
||
| private void writeIniValue(String key, String value) { | ||
| write(key, true, restrictCharset); | ||
| writeSeparator(); | ||
| write(value, false, restrictCharset); | ||
| writeLineBreak(); | ||
| } | ||
| 
     | 
||
| private void writeIniKey(String keyValue) { | ||
| try { | ||
| // inserts a line break to make sure ini file is correct format | ||
| writeLineBreak(); | ||
| writer.write('['); | ||
| write(keyValue, true, restrictCharset); | ||
| writer.write(']'); | ||
| writeLineBreak(); | ||
| } catch (IOException e) { | ||
| throw new UncheckedIOException(e); | ||
| } | ||
| } | ||
| 
     | 
||
| private void writeSeparator() { | ||
| try { | ||
| writer.write(' '); | ||
| writer.write('='); | ||
| writer.write(' '); | ||
| } catch (IOException e) { | ||
| throw new RuntimeException(e); | ||
| } | ||
| } | ||
| 
     | 
||
| private void writeLineBreak() { | ||
| try { | ||
| writer.write('\n'); | ||
| } catch (IOException e) { | ||
| throw new UncheckedIOException(e); | ||
| } | ||
| } | ||
| } | ||
| } | ||
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
        
          
          
            65 changes: 65 additions & 0 deletions
          
          65 
        
  pkl-core/src/main/java/org/pkl/core/util/ini/IniUtils.java
  
  
      
      
   
        
      
      
    
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,65 @@ | ||
| /** | ||
| * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. | ||
| * | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * | ||
| * https://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
| package org.pkl.core.util.ini; | ||
| 
     | 
||
| public class IniUtils { | ||
| // bitmap 32 bit need to escape ' ', ';' | ||
| private static final int[] bitmapEscapeSpace = new int[] {9728, 738197900, 268435456, 0}; | ||
| 
     | 
||
| private static final int[] bitmapNoEscapeSpace = new int[] {9728, 738197644, 268435456, 0}; | ||
| 
     | 
||
| private static final char[] hexDigitTable = | ||
| new char[] {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; | ||
| 
     | 
||
| private static final char[] hashTable = | ||
| new char[] { | ||
| ' ', 0, '"', '#', 0, 0, 0, '\'', 0, 't', 'n', 0, 0, 'r', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, | ||
| ':', ';', '\\', '=', 0, 0 | ||
| }; | ||
| 
     | 
||
| public static String renderPropertiesKeyOrValue( | ||
| String value, boolean escapeSpace, boolean restrictCharset) { | ||
| if (value.isEmpty()) { | ||
| return ""; | ||
| } | ||
| var builder = new StringBuilder(); | ||
| 
     | 
||
| if (!escapeSpace && value.charAt(0) == ' ') { | ||
| builder.append('\\'); | ||
| } | ||
| 
     | 
||
| for (var i = 0; i < value.length(); i++) { | ||
| var c = value.charAt(i); | ||
| var bitmap = escapeSpace ? bitmapEscapeSpace : bitmapNoEscapeSpace; | ||
| var isEscapeChar = c < 128 && (bitmap[c >> 5] & (1 << c)) != 0; | ||
| 
     | 
||
| if (isEscapeChar) { | ||
| builder.append('\\').append(hashTable[c % 32]); | ||
| } else if (restrictCharset && (c < 32 || c > 126)) { | ||
| builder | ||
| .append('\\') | ||
| .append('u') | ||
| .append(hexDigitTable[c >> 12 & 0xF]) | ||
| .append(hexDigitTable[c >> 8 & 0xF]) | ||
| .append(hexDigitTable[c >> 4 & 0xF]) | ||
| .append(hexDigitTable[c & 0xF]); | ||
| } else { | ||
| builder.append(c); | ||
| } | ||
| } | ||
| return builder.toString(); | ||
| } | ||
| } | 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,54 @@ | ||
| package org.pkl.core | ||
| 
     | 
||
| import org.assertj.core.api.Assertions.assertThat | ||
| import org.junit.jupiter.api.Test | ||
| import org.junit.jupiter.api.assertThrows | ||
| import org.pkl.core.util.IoUtils | ||
| import java.io.StringWriter | ||
| 
     | 
||
| class IniRendererTest { | ||
| @Test | ||
| fun `render document`() { | ||
| val evaluator = Evaluator.preconfigured() | ||
| val module = evaluator.evaluate(ModuleSource.modulePath("org/pkl/core/iniRendererTest.pkl")) | ||
| val writer = StringWriter() | ||
| val renderer = ValueRenderers.ini(writer, true, false) | ||
| 
     | 
||
| renderer.renderDocument(module) | ||
| val output = writer.toString() | ||
| val expected = IoUtils.readClassPathResourceAsString(javaClass, "iniRendererTest.ini") | ||
| 
     | 
||
| 
     | 
||
| assertThat(output).isEqualTo(expected) | ||
| } | ||
| 
     | 
||
| @Test | ||
| fun `render unsupported document values`() { | ||
| val unsupportedValues = listOf( | ||
| "List()", "new Listing {}", "Map()", "new Mapping {}", "Set()", | ||
| "new PropertiesRenderer {}", "new Dynamic {}" | ||
| ) | ||
| 
     | 
||
| unsupportedValues.forEach { | ||
| val evaluator = Evaluator.preconfigured() | ||
| val renderer = ValueRenderers.ini(StringWriter(), true, false) | ||
| 
     | 
||
| val module = evaluator.evaluate(ModuleSource.text("value = $it")) | ||
| assertThrows<RendererException> { renderer.renderValue(module) } | ||
| } | ||
| } | ||
| 
     | 
||
| @Test | ||
| fun `rendered document ends in newline`() { | ||
| val module = Evaluator.preconfigured() | ||
| .evaluate(ModuleSource.text("foo { bar = 0 }")) | ||
| 
     | 
||
| for (omitNullProperties in listOf(false, true)) { | ||
| for (restrictCharSet in listOf(false, true)) { | ||
| val writer = StringWriter() | ||
| ValueRenderers.ini(writer, omitNullProperties, restrictCharSet).renderDocument(module) | ||
| assertThat(writer.toString()).endsWith("\n") | ||
| } | ||
| } | ||
| } | ||
| } | 
      
      Oops, something went wrong.
        
    
  
  Add this suggestion to a batch that can be applied as a single commit.
  This suggestion is invalid because no changes were made to the code.
  Suggestions cannot be applied while the pull request is closed.
  Suggestions cannot be applied while viewing a subset of changes.
  Only one suggestion per line can be applied in a batch.
  Add this suggestion to a batch that can be applied as a single commit.
  Applying suggestions on deleted lines is not supported.
  You must change the existing code in this line in order to create a valid suggestion.
  Outdated suggestions cannot be applied.
  This suggestion has been applied or marked resolved.
  Suggestions cannot be applied from pending reviews.
  Suggestions cannot be applied on multi-line comments.
  Suggestions cannot be applied while the pull request is queued to merge.
  Suggestion cannot be applied right now. Please check back later.
  
    
  
    
Uh oh!
There was an error while loading. Please reload this page.