compiler.ts 5.6 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1
import os from 'os'
fxy060608's avatar
fxy060608 已提交
2
import fs from 'fs-extra'
fxy060608's avatar
fxy060608 已提交
3
import path from 'path'
fxy060608's avatar
fxy060608 已提交
4 5
import AdmZip from 'adm-zip'
import { sync } from 'fast-glob'
fxy060608's avatar
fxy060608 已提交
6 7
import { once } from '@dcloudio/uni-shared'
import type { parse, bundle, UtsTarget } from '@dcloudio/uts'
fxy060608's avatar
fxy060608 已提交
8 9
import { normalizePath } from '@dcloudio/uni-cli-shared'
import { camelize } from '@vue/shared'
fxy060608's avatar
fxy060608 已提交
10

fxy060608's avatar
fxy060608 已提交
11 12
export function getUtsCompiler(): {
  parse: typeof parse
fxy060608's avatar
fxy060608 已提交
13
  bundle: typeof bundle
fxy060608's avatar
fxy060608 已提交
14 15 16 17 18
  UtsTarget: typeof UtsTarget
} {
  // eslint-disable-next-line no-restricted-globals
  return require('@dcloudio/uts')
}
fxy060608's avatar
fxy060608 已提交
19 20 21 22 23 24 25 26 27 28
export async function compile(filename: string) {
  if (!process.env.UNI_HBUILDERX_PLUGINS) {
    return
  }
  const { bundle, UtsTarget } = getUtsCompiler()
  const inputDir = process.env.UNI_INPUT_DIR
  const outputDir = process.env.UNI_OUTPUT_DIR
  let time = Date.now()
  await bundle({
    target: UtsTarget.KOTLIN,
fxy060608's avatar
fxy060608 已提交
29
    input: {
fxy060608's avatar
fxy060608 已提交
30 31
      root: inputDir,
      filename,
fxy060608's avatar
fxy060608 已提交
32 33
    },
    output: {
fxy060608's avatar
fxy060608 已提交
34
      outDir: outputDir,
fxy060608's avatar
fxy060608 已提交
35
      package: parsePackage(filename),
fxy060608's avatar
fxy060608 已提交
36
      sourceMap: true,
fxy060608's avatar
fxy060608 已提交
37
      extname: 'kt',
fxy060608's avatar
fxy060608 已提交
38
      imports: ['kotlinx.coroutines.*', 'io.dcloud.uts.runtime.*'],
fxy060608's avatar
fxy060608 已提交
39
      logFilename: true,
fxy060608's avatar
fxy060608 已提交
40 41
    },
  })
fxy060608's avatar
fxy060608 已提交
42 43
  console.log('uts compile time: ' + (Date.now() - time) + 'ms')
  const kotlinFile = resolveKotlinFile(filename, inputDir, outputDir)
fxy060608's avatar
fxy060608 已提交
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
  if (process.env.NODE_ENV === 'production') {
    // 生产模式下,需要将 kt 文件转移到 src 下
    fs.mkdirSync(path.resolve(kotlinFile, '../src'))
    if (fs.existsSync(kotlinFile)) {
      fs.moveSync(kotlinFile, path.resolve(kotlinFile, '../src/index.kt'))
    }
    const kotlinMapFile = kotlinFile + '.map'
    if (fs.existsSync(kotlinMapFile)) {
      fs.moveSync(
        kotlinMapFile,
        path.resolve(kotlinFile, '../src/index.map.kt')
      )
    }

    const copies = ['assets', 'libs', 'res']
    const moduleDir = path.dirname(filename)
    const outputModuleDir = path.dirname(kotlinFile)
    fs.readdirSync(moduleDir).forEach((file) => {
      if (copies.includes(file)) {
        fs.copySync(
          path.join(moduleDir, file),
          path.join(outputModuleDir, file)
        )
      }
    })
  } else if (process.env.NODE_ENV === 'development') {
    // 开发模式下,需要生成 dex
    if (fs.existsSync(kotlinFile)) {
fxy060608's avatar
fxy060608 已提交
72
      time = Date.now()
fxy060608's avatar
fxy060608 已提交
73
      const { getDefaultJar, compile } = getCompilerServer()
fxy060608's avatar
fxy060608 已提交
74
      const jarFile = resolveJarPath(kotlinFile)
fxy060608's avatar
fxy060608 已提交
75 76 77 78 79 80 81 82 83 84 85
      const options = {
        kotlinc: resolveKotlincArgs(
          kotlinFile,
          getDefaultJar().concat(resolveLibs(filename))
        ),
        d8: resolveD8Args(jarFile),
      }
      const res = await compile(options, process.env.UNI_INPUT_DIR)
      console.log('dex compile time: ' + (Date.now() - time) + 'ms')
      time = Date.now()
      if (res) {
fxy060608's avatar
fxy060608 已提交
86 87 88 89 90
        try {
          fs.unlinkSync(jarFile)
          // 短期内先不删除,方便排查问题
          // fs.unlinkSync(kotlinFile)
        } catch (e) {}
fxy060608's avatar
fxy060608 已提交
91 92 93 94
        const dexFile = resolveDexFile(jarFile)
        if (fs.existsSync(dexFile)) {
          return normalizePath(path.relative(outputDir, dexFile))
        }
fxy060608's avatar
fxy060608 已提交
95
      }
fxy060608's avatar
fxy060608 已提交
96 97
    }
  }
fxy060608's avatar
fxy060608 已提交
98
}
fxy060608's avatar
fxy060608 已提交
99

fxy060608's avatar
fxy060608 已提交
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
function resolveKotlincArgs(filename: string, jars: string[]) {
  return [
    filename,
    '-cp',
    resolveClassPath(jars),
    '-d',
    resolveJarPath(filename),
    '-kotlin-home',
    '/Applications/HBuilderX-Alpha.app/Contents/HBuilderX/plugins/uniAppRun-Extension/kotlinc',
  ]
}

function resolveD8Args(filename: string) {
  return [
    filename,
    '--no-desugaring',
    '--min-api',
    '19',
    '--output',
    resolveDexPath(filename),
  ]
}

function resolveLibs(filename: string) {
  const libsPath = path.resolve(path.dirname(filename), 'libs')
  const libs: string[] = []
  if (fs.existsSync(libsPath)) {
    libs.push(...sync('*.jar', { cwd: libsPath, absolute: true }))
    const zips = sync('*.aar', { cwd: libsPath })
    zips.forEach((name) => {
      const outputPath = resolveAndroidArchiveOutputPath(name)
      if (!fs.existsSync(outputPath)) {
        // 解压
        const zip = new AdmZip(path.resolve(libsPath, name))
        zip.extractAllTo(outputPath, true)
      }
    })
    if (zips.length) {
      libs.push(
        ...sync('*/*.jar', {
          cwd: resolveAndroidArchiveOutputPath(),
          absolute: true,
        })
      )
    }
  }
  return libs
}

function resolveAndroidArchiveOutputPath(aar?: string) {
  return path.resolve(
    process.env.UNI_OUTPUT_DIR,
    '../.uts/aar',
    aar ? aar.replace('.aar', '') : ''
  )
}
fxy060608's avatar
fxy060608 已提交
156 157 158 159
function resolveDexFile(jarFile: string) {
  return normalizePath(path.resolve(path.dirname(jarFile), 'classes.dex'))
}

fxy060608's avatar
fxy060608 已提交
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
function resolveKotlinFile(
  filename: string,
  inputDir: string,
  outputDir: string
) {
  return path
    .resolve(outputDir, path.relative(inputDir, filename))
    .replace(path.extname(filename), '.kt')
}

function resolveDexPath(filename: string) {
  return path.dirname(filename)
}

function resolveJarPath(filename: string) {
  return filename.replace(path.extname(filename), '.jar')
}

fxy060608's avatar
fxy060608 已提交
178 179
function resolveClassPath(jars: string[]) {
  return jars.join(os.platform() === 'win32' ? ';' : ':')
fxy060608's avatar
fxy060608 已提交
180 181
}

fxy060608's avatar
fxy060608 已提交
182 183 184
const getCompilerServer = once(() => {
  // eslint-disable-next-line no-restricted-globals
  return require(path.resolve(
fxy060608's avatar
fxy060608 已提交
185
    process.env.UNI_HBUILDERX_PLUGINS,
fxy060608's avatar
fxy060608 已提交
186 187 188 189 190 191 192 193
    'uniAppRun-Extension/out/main.js'
  )) as {
    getDefaultJar(): string[]
    compile(
      options: { kotlinc: string[]; d8: string[] },
      projectPath: string
    ): Promise<boolean>
  }
fxy060608's avatar
fxy060608 已提交
194
})
fxy060608's avatar
fxy060608 已提交
195 196 197 198 199 200 201 202 203

export function parsePackage(filepath: string) {
  const parts = normalizePath(filepath).split('/')
  const index = parts.findIndex((part) => part === 'uni_modules')
  if (index > -1) {
    return 'uts.modules.' + camelize(parts[index + 1])
  }
  return ''
}