浏览代码

Realize the method of appending and overwriting system hosts.

oldj 3 年之前
父节点
当前提交
4eec75378d

+ 24 - 1
src/main/actions/hosts/setSystemHosts.ts

@@ -33,6 +33,8 @@ interface IWriteResult {
   new_content?: string
   new_content?: string
 }
 }
 
 
+const CONTENT_START = '# --- SWITCHHOSTS_CONTENT_START ---'
+
 let sudo_pswd: string = ''
 let sudo_pswd: string = ''
 
 
 const checkAccess = async (fn: string): Promise<boolean> => {
 const checkAccess = async (fn: string): Promise<boolean> => {
@@ -160,7 +162,7 @@ const write = async (
 
 
   try {
   try {
     await fs.promises.writeFile(sys_hosts_path, content, 'utf-8')
     await fs.promises.writeFile(sys_hosts_path, content, 'utf-8')
-  } catch (e) {
+  } catch (e: any) {
     console.error(e)
     console.error(e)
     let code = 'fail'
     let code = 'fail'
     if (e.code === 'EPERM' || e.message.include('operation not permitted')) {
     if (e.code === 'EPERM' || e.message.include('operation not permitted')) {
@@ -177,10 +179,31 @@ const write = async (
   return { success: true, old_content, new_content: content }
   return { success: true, old_content, new_content: content }
 }
 }
 
 
+const makeAppendContent = async (content: string): Promise<string> => {
+  const sys_hosts_path = await getPathOfSystemHosts()
+  const old_content = await fs.promises.readFile(sys_hosts_path, 'utf-8')
+
+  let index = old_content.indexOf(CONTENT_START)
+  let new_content =
+    index > -1 ? old_content.substring(0, index).trimEnd() : old_content
+
+  if (!content) {
+    return new_content + '\n'
+  }
+
+  return `${new_content}\n\n${CONTENT_START}\n\n${content}`
+}
+
 const setSystemHosts = async (
 const setSystemHosts = async (
   content: string,
   content: string,
   options?: IHostsWriteOptions,
   options?: IHostsWriteOptions,
 ): Promise<IWriteResult> => {
 ): Promise<IWriteResult> => {
+  let write_mode = await configGet('write_mode')
+  console.log(`write_mode: ${write_mode}`)
+  if (write_mode === 'append') {
+    content = await makeAppendContent(content)
+  }
+
   let result = await write(content, options)
   let result = await write(content, options)
   let { success, old_content } = result
   let { success, old_content } = result
 
 

+ 0 - 2
src/renderer/components/List/index.tsx

@@ -84,8 +84,6 @@ const List = (props: Props) => {
     }
     }
   }
   }
 
 
-  const toSetWriteMode = async () => {}
-
   const writeHostsToSystem = async (
   const writeHostsToSystem = async (
     list?: IHostsListObject[],
     list?: IHostsListObject[],
     options?: IHostsWriteOptions,
     options?: IHostsWriteOptions,

+ 24 - 24
src/renderer/components/Pref/General.tsx

@@ -68,59 +68,59 @@ const General = (props: IProps) => {
       </FormControl>
       </FormControl>
 
 
       <FormControl>
       <FormControl>
-        <HStack>
-          <FormLabel w={label_width}>{lang.choice_mode}</FormLabel>
+        <HStack alignItems={'flex-start'}>
+          <FormLabel w={label_width}>{lang.write_mode}</FormLabel>
           <VStack align="left">
           <VStack align="left">
             <RadioGroup
             <RadioGroup
-              value={data.choice_mode.toString()}
+              value={data.write_mode || ''}
               onChange={(v) =>
               onChange={(v) =>
                 onChange({
                 onChange({
-                  choice_mode: parseInt(
-                    v.toString(),
-                  ) as ConfigsType['choice_mode'],
+                  write_mode: v as ConfigsType['write_mode'],
                 })
                 })
               }
               }
             >
             >
               <HStack spacing={10}>
               <HStack spacing={10}>
-                <Radio value="1">
-                  <Box>{lang.choice_mode_single}</Box>
+                <Radio value="append">
+                  <Box>{lang.append}</Box>
                 </Radio>
                 </Radio>
-                <Radio value="2">
-                  <Box>{lang.choice_mode_multiple}</Box>
+                <Radio value="overwrite">
+                  <Box>{lang.overwrite}</Box>
                 </Radio>
                 </Radio>
               </HStack>
               </HStack>
             </RadioGroup>
             </RadioGroup>
-            <FormHelperText>{lang.choice_mode_desc}</FormHelperText>
+            <FormHelperText>
+              {data.write_mode === 'append' && lang.write_mode_append_help}
+              {data.write_mode === 'overwrite' &&
+                lang.write_mode_overwrite_help}
+            </FormHelperText>
           </VStack>
           </VStack>
         </HStack>
         </HStack>
       </FormControl>
       </FormControl>
 
 
       <FormControl pb={6}>
       <FormControl pb={6}>
-        <HStack>
-          <FormLabel w={label_width}>{lang.write_mode}</FormLabel>
+        <HStack alignItems={'flex-start'}>
+          <FormLabel w={label_width}>{lang.choice_mode}</FormLabel>
           <VStack align="left">
           <VStack align="left">
             <RadioGroup
             <RadioGroup
-              value={data.write_mode || ''}
+              value={data.choice_mode.toString()}
               onChange={(v) =>
               onChange={(v) =>
                 onChange({
                 onChange({
-                  write_mode: v as ConfigsType['write_mode'],
+                  choice_mode: parseInt(
+                    v.toString(),
+                  ) as ConfigsType['choice_mode'],
                 })
                 })
               }
               }
             >
             >
               <HStack spacing={10}>
               <HStack spacing={10}>
-                <Radio value="append">
-                  <Box>{lang.append}</Box>
+                <Radio value="1">
+                  <Box>{lang.choice_mode_single}</Box>
                 </Radio>
                 </Radio>
-                <Radio value="overwrite">
-                  <Box>{lang.overwrite}</Box>
+                <Radio value="2">
+                  <Box>{lang.choice_mode_multiple}</Box>
                 </Radio>
                 </Radio>
               </HStack>
               </HStack>
             </RadioGroup>
             </RadioGroup>
-            <FormHelperText>
-              {data.write_mode === 'append' && lang.write_mode_append_help}
-              {data.write_mode === 'overwrite' &&
-                lang.write_mode_overwrite_help}
-            </FormHelperText>
+            <FormHelperText>{lang.choice_mode_desc}</FormHelperText>
           </VStack>
           </VStack>
         </HStack>
         </HStack>
       </FormControl>
       </FormControl>

+ 9 - 0
src/renderer/components/Pref/styles.less

@@ -4,3 +4,12 @@
   text-decoration: underline;
   text-decoration: underline;
   color: inherit;
   color: inherit;
 }
 }
+
+:global {
+  label {
+    span.chakra-radio__control {
+      width: 16px;
+      height: 16px;
+    }
+  }
+}

+ 1 - 2
src/renderer/components/SetWriteMode.tsx

@@ -19,7 +19,6 @@ import {
 } from '@chakra-ui/react'
 } from '@chakra-ui/react'
 import { agent } from '@renderer/core/agent'
 import { agent } from '@renderer/core/agent'
 import useOnBroadcast from '@renderer/core/useOnBroadcast'
 import useOnBroadcast from '@renderer/core/useOnBroadcast'
-import { IHostsListObject } from '@root/common/data'
 import events from '@root/common/events'
 import events from '@root/common/events'
 import React, { useState } from 'react'
 import React, { useState } from 'react'
 import styles from './SetWriteMode.less'
 import styles from './SetWriteMode.less'
@@ -33,7 +32,7 @@ interface IPendingData {
 }
 }
 
 
 const SetWriteMode = (props: Props) => {
 const SetWriteMode = (props: Props) => {
-  const { configs, updateConfigs } = useModel('useConfigs')
+  const { updateConfigs } = useModel('useConfigs')
   const { lang } = useModel('useI18n')
   const { lang } = useModel('useI18n')
   const [is_show, setIsShow] = useState(false)
   const [is_show, setIsShow] = useState(false)
   const ipt_ref = React.useRef<HTMLInputElement>(null)
   const ipt_ref = React.useRef<HTMLInputElement>(null)