1 /*
2  * Copyright (c) Meta Platforms, Inc. and affiliates.
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.facebook.ktfmt.intellij
18 
19 import com.facebook.ktfmt.intellij.KtfmtSettings.EnabledState.Disabled
20 import com.facebook.ktfmt.intellij.KtfmtSettings.EnabledState.Enabled
21 import com.facebook.ktfmt.intellij.KtfmtSettings.EnabledState.Unknown
22 import com.facebook.ktfmt.intellij.KtfmtSettingsMigration.MigrationState
23 import com.intellij.openapi.components.BaseState
24 import com.intellij.openapi.components.Service
25 import com.intellij.openapi.components.SimplePersistentStateComponent
26 import com.intellij.openapi.components.State
27 import com.intellij.openapi.components.Storage
28 import com.intellij.openapi.components.StoragePathMacros
29 
30 @Service(Service.Level.PROJECT)
31 @State(name = "KtfmtSettingsMigration", storages = [(Storage(StoragePathMacros.WORKSPACE_FILE))])
32 internal class KtfmtSettingsMigration :
33     SimplePersistentStateComponent<MigrationState>(MigrationState()) {
34 
35   // ---------
36   // Changelog
37   // ---------
38   //
39   // v2 enabled [bool] -> enableKtfmt [enum], custom styles (0.52+)
40   // v1 initial version - enabled is a boolean, only preset styles
41   var stateVersion
<lambda>null42     get() = state.stateVersion.takeIf { it > 0 } ?: 1
43     set(value) {
44       state.stateVersion = value
45     }
46 
47   @Suppress("DEPRECATION") // Accessing deprecated properties
migrateFromV1ToCurrentnull48   fun migrateFromV1ToCurrent(v1State: KtfmtSettings.State): KtfmtSettings.State {
49     val migrated =
50         KtfmtSettings.State().apply {
51           copyFrom(v1State)
52 
53           enableKtfmt =
54               when (v1State.enabled) {
55                 "true" -> Enabled
56                 "false" -> Disabled
57                 else -> Unknown
58               }
59           enabled = null
60         }
61     state.stateVersion = CURRENT_VERSION
62     return migrated
63   }
64 
65   class MigrationState : BaseState() {
66     var stateVersion by property(-1)
67   }
68 
69   companion object {
70     const val CURRENT_VERSION = 2
71   }
72 }
73