github.com/fzfile/BaiduPCS-Go@v0.0.0-20200606205115-4408961cf336/pcsliner/pcsliner.go (about)

     1  // Package pcsliner 命令行 readline 工具包
     2  package pcsliner
     3  
     4  import (
     5  	"github.com/peterh/liner"
     6  )
     7  
     8  // PCSLiner 封装 *liner.State, 提供更简便的操作
     9  type PCSLiner struct {
    10  	State   *liner.State
    11  	History *LineHistory
    12  
    13  	tmode liner.ModeApplier
    14  	lmode liner.ModeApplier
    15  
    16  	paused bool
    17  }
    18  
    19  // NewLiner 返回 *PCSLiner, 默认设置允许 Ctrl+C 结束
    20  func NewLiner() *PCSLiner {
    21  	pl := &PCSLiner{}
    22  	pl.tmode, _ = liner.TerminalMode()
    23  
    24  	line := liner.NewLiner()
    25  	pl.lmode, _ = liner.TerminalMode()
    26  
    27  	line.SetMultiLineMode(true)
    28  	line.SetCtrlCAborts(true)
    29  
    30  	pl.State = line
    31  
    32  	return pl
    33  }
    34  
    35  // Pause 暂停服务
    36  func (pl *PCSLiner) Pause() error {
    37  	if pl.paused {
    38  		panic("PCSLiner already paused")
    39  	}
    40  
    41  	pl.paused = true
    42  	pl.DoWriteHistory()
    43  
    44  	return pl.tmode.ApplyMode()
    45  }
    46  
    47  // Resume 恢复服务
    48  func (pl *PCSLiner) Resume() error {
    49  	if !pl.paused {
    50  		panic("PCSLiner is not paused")
    51  	}
    52  
    53  	pl.paused = false
    54  
    55  	return pl.lmode.ApplyMode()
    56  }
    57  
    58  // Close 关闭服务
    59  func (pl *PCSLiner) Close() (err error) {
    60  	err = pl.State.Close()
    61  	if err != nil {
    62  		return err
    63  	}
    64  
    65  	if pl.History != nil && pl.History.historyFile != nil {
    66  		return pl.History.historyFile.Close()
    67  	}
    68  
    69  	return nil
    70  }